pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.liu</groupId>
<artifactId>exportExcel-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
编写一个属性类,用来定义我们要集成的功能模块所需要的配置项,并且使用@ConfigurationProperties
注解来指定配置文件中的前缀
@Component
@ConfigurationProperties(prefix = "exportexcel")
public class ExcelProperties {
private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
后续yml
文件中可以直接配置相关属性。
示例:
exportexcel:
file-path: "out.xlsx"
编写一个业务功能类,用来实现我们要集成的功能模块的具体业务逻辑,将数据库中的数据导出为excel文件
public class EasyExcelExport {
public <T> void exportExcel(OutputStream outputStream, Class<T> clazz, List<T> data) throws IOException, IOException {
try {
EasyExcel.write(outputStream, clazz).sheet("data").doWrite(data);
} finally {
outputStream.flush();
outputStream.close();
}
}
}
编写一个自动配置类,根据属性类和业务功能类,创建响应的Bean
对象
@Configuration //表明是一个配置类
@EnableConfigurationProperties(ExcelProperties.class) //来启用属性类
public class excelAutoConfiguration {
private final ExcelProperties excelProperties;
public excelAutoConfiguration(ExcelProperties excelProperties){
this.excelProperties = excelProperties;
}
@Bean
@ConditionalOnMissingBean
public EasyExcelExport easyExcelExport() {
return new EasyExcelExport();
}
}
创建一个自定义的Starter
项目时,需要在Resource/META-INF
目录下创建一个spring.factories
的文件,用来指定我们的自动配置类,让Spring Boot
能够在启动时自定扫描并加载。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.liu.exportExcel.config.excelAutoConfiguration
标签:outputStream,自定义,filePath,spring,boot,org,public,Starter
From: https://www.cnblogs.com/solutide/p/18360864