导入导出笔记-easyExcel初探(表格导入和模板化导出)
前言
本文使用的EasyExcel Alibaba和EasyPoi Apache技术栈分析
-
EasyExcel Dependency
-
EasyPoi Dependency
1、需求一:表格化需求导入导出(难度星级:☆)
导入导出模板
实体对象
这里我们用到了一个注解com.alibaba.excel.annotation.ExcelProperty
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcelProperty {
/**
* The name of the sheet header.
*
* <p>
* write: It automatically merges when you have more than one head
* <p>
* read: When you have multiple heads, take the first one
*
* @return The name of the sheet header
*/
String[] value() default {""};
/**
* Index of column
*
* Read or write it on the index of column,If it's equal to -1, it's sorted by Java class.
*
* priority: index > order > default sort
*
* @return Index of column
*/
int index() default -1;
/**
* Defines the sort order for an column.
*
* priority: index > order > default sort
*
* @return Order of column
*/
int order() default Integer.MAX_VALUE;
/**
* Force the current field to use this converter.
*
* @return Converter
*/
Class<? extends Converter> converter() default AutoConverter.class;
/**
*
* default @see com.alibaba.excel.util.TypeUtil if default is not meet you can set format
*
* @return Format string
* @deprecated please use {@link com.alibaba.excel.annotation.format.DateTimeFormat}
*/
@Deprecated
String format() default "";
}
此处使用到的value注解,其余属性不扩展,有想了解的东西可以关注公众号“技术小邱”了解
注意,导出时此处value值要和excel值完全匹配,包括空格
- 导入:解析excel
EasyExcel.read(file.getInputStream()).head(Student.class).autoCloseStream(true) .autoTrim(true).sheet().doReadSync()
- 导出:生成excel
WriteSheet studentSheet = EasyExcel.writerSheet("学生信息").head(ClaimReportListExportDTO.class).build();
excelWriter.write(studentList, studentSheet);
2、模板化导出(难度:☆☆☆)
模板样式
首先我们需要更换模板,填充代入代码
第一步:获取模板输入流信息(读取模板信息)
InputStream in = this.getClass().getResourceAsStream(fileName)
第二步:转换成输出流(写入目标文件)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > -1) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
in.close();
第三步:目标写入
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(studentInfoList, fillConfig, writeSheet);
ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(byteArrayInputStream)
.autoCloseStream(Boolean.TRUE).build();
excelWriter.finish();
这样就完成对应的导出了
以上均可以通过EasyExcel实现,EasyPoi目前运用比较多的是列表动态扩展,后面的博客将会讲到
大家可以关注下公众号,回复EasyExcel获取更多资料
往事随风、无忧无恼