1.导入依赖
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> easyexcel</ artifactId>
< version> 3.0.1</ version>
</ dependency>
2.代码实现
package com. jiayou. peis. manage. biz. cotroller ;
import com. alibaba. excel. EasyExcel ;
import com. alibaba. excel. ExcelWriter ;
import com. alibaba. excel. write. metadata. WriteSheet ;
import org. apache. commons. io. IOUtils ;
import org. springframework. core. io. ClassPathResource ;
import java. io. IOException ;
import java. io. InputStream ;
import java. util. HashMap ;
import java. util. Map ;
public class Test {
public static void main ( String [ ] args) {
export ( ) ;
}
private static void export ( ) {
ExcelWriter excelWriter = null ;
InputStream templateInputStream = null ;
Map < String , Object > map = new HashMap < > ( ) ;
map. put ( "name" , "张三" ) ;
map. put ( "sex" , "男" ) ;
map. put ( "age" , "20" ) ;
try {
templateInputStream = new ClassPathResource ( "template/data_template.xlsx" ) . getInputStream ( ) ;
if ( templateInputStream. available ( ) == 0 ) {
log. error ( "获取模板失败" ) ;
}
String fileName = "测试报告" + System . currentTimeMillis ( ) + ".xlsx" ;
String path = "D:\\" ;
String filePath = path + fileName;
excelWriter = EasyExcel . write ( filePath) . withTemplate ( templateInputStream) . build ( ) ;
WriteSheet firstSheet = EasyExcel . writerSheet ( 0 ) . build ( ) ;
excelWriter. fill ( map, firstSheet) ;
} catch ( IOException e) {
log. error ( "获取模板:examreport 失败。" ) ;
e. printStackTrace ( ) ;
} finally {
excelWriter. finish ( ) ;
IOUtils . closeQuietly ( templateInputStream) ;
}
}
}
3.模板