到此 灵熙云工作室 - 实践出真理 查看全文内容
日常开发中常会遇到Excel导入导出的需求,得空写个前后端通用版的Excel导入导出demo,供之后开发效率事半功倍
功能实现 数据表初始数据
CREATE TABLE `student` ( `sno` varchar(10) NOT NULL, `sname` varchar(20) DEFAULT NULL, `sage` varchar(11) DEFAULT NULL, `ssex` varchar(5) DEFAULT NULL, PRIMARY KEY (`sno`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
注:字段全为字符类型,避免解析数据保存到数据库表时需过多的数据类型转换逻辑
依赖文件配置文件spring-boot-project cn.goitman 0.0.1-SNAPSHOT 4.0.0 poi-importAndExport-demo org.springframework.boot spring-boot-starter-web com.alibaba fastjson 1.2.76 org.apache.poi poi 3.9 org.apache.poi poi-ooxml 3.9 dom4j dom4j 1.6.1 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 tk.mybatis mapper-spring-boot-starter RELEASE mysql mysql-connector-java 5.1.47
server:
port: 8080
spring:
datasource:
url: jdbc:mysql:///数据库?characterEncoding=utf8&useUnicode=true
username:
password:
driver-class-name: com.mysql.jdbc.Driver
mybatis:
# xml文件地址
mapper-locations: classpath:mapper/*Mapper.xml
# 打印mybatis的执行sql语句
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 开启驼峰自动转换
map-underscore-to-camel-case: true
# 文件保存地址
file:
filePath: E:/
引导类
package cn.goitman;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("cn.goitman.mapper") // 指定扫描的Mapper类的包的路径,在每个Mapper类上添加注解@Mapper
public class ExcelApplication {
public static void main(String[] args) {
SpringApplication.run(ExcelApplication.class,args);
}
}
四个自定义注解
EnableExport(允许导出类注解)
实体类上必须定义此注解,因工具类会判断当前类是否为允许导出
package cn.goitman.annotation;
import cn.goitman.enums.ColorEnum;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE) // 用于类
@Retention(RetentionPolicy.RUNTIME) // 运行时
public @interface EnableExport {
// 标题/文件名
String fileName();
// 背景颜色,默认蓝色
ColorEnum cellColor() default ColorEnum.BLUE;
}



