Apache POI提供了HSSF、XSSF以及SXSSF三种方式操作Excel。他们的区别如下:
- HSSF:是操作Excel97-2003版本,扩展名为.xls,一个sheet最大行数65536,最大列数256。
- XSSF:是操作Excel2007版本开始,扩展名为.xlsx,一个sheet最大行数1048576,最大列数16384。
- SXSSF:是在XSSF基础上,POI3.8版本开始提供的一种支持低内存占用的操作方式,扩展名为.xlsx。
SXSSF操作可以实现海量数据处理,而EasyExcel
作为三方包来封装了SXSSF操作。
引入依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.3</version>
</dependency>
注解实现
实体类添加注解:
@Data
@HeadRowHeight(30) //表头行高
@ContentRowHeight(15) //内容行高
@ColumnWidth(18) //列宽
@ContentFontStyle(fontHeightInPoints = (short) 12) //字体大小
@ApiModel(value = "ExportEntity", description = "ExportEntity")
public class ExportEntity {
/** id */
@ApiModelProperty(value = "id")
@ExcelProperty("id")
private Long id;
/** 名称 */
@ApiModelProperty(value = "名称")
@ExcelProperty("名称")
private String name;
/** 年龄 */
@ApiModelProperty(value = "年龄")
@ExcelProperty("年龄")
private Integer age;
/** 性别 */
@ApiModelProperty(value = "性别")
@ExcelIgnore
private String sex;
-
默认所有字段都会和excel去匹配,使用@ExcelIgnore注解会忽略该字段。
-
@ExcelProperty:指定当前字段对应 excel 中的那一列。可以根据名字或者Index去匹配,默认第一个字段就是index=0,以此类推。⚠️要么全部不写,要么全部用index,要么全部用名字去匹配,切勿混合使用。
导出方法:
大批量文件下载到本地,此时也是逐步的追加数据。
public void export() {
// 生成excel初始文件
String filePath = "/tmp/" + UUID.randomUUID().toString().replace("-", "") + ".xlsx";
ExcelWriterBuilder writeBuilder =
EasyExcel.write(filePath).excelType(ExcelTypeEnum.XLSX).head(OrderExportVO.class).autoCloseStream(true);
ExcelWriter writer = writeBuilder.build();
WriteSheet sheet = EasyExcel.writerSheet().build();
// 分页写入所有数据到EXCEL
try {
long cursorId = 0L;
while (true) {
//分页查询
LambdaQueryWrapper<OrderTestPO> queryWrapper = new LambdaQueryWrapper<OrderTestPO>()
.gt(OrderTestPO::getOrderId, cursorId)
.orderByAsc(OrderTestPO::getOrderId)
.last(" LIMIT 1000 ");
List<OrderTestPO> rows = orderTestMapper.selectList(queryWrapper);
List<OrderExportVO> voList = OrderExportVO.from(rows);
if (CollectionUtils.isEmpty(voList)) {
break;
}
//流式追加
writer.write(voList, sheet);
cursorId = rows.get(rows.size() - 1).getOrderId();
}
} finally {
writer.finish();
}
}
下载到response对象:
@Override
public void export(HttpServletResponse response) {
List<Export> list = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
Export export = new Export(i,"张三","20");
list.add(export);
}
try {
//HttpServletResponse消息头参数设置
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
String fileName = "导出列表"+ ".xlsx";
fileName = new String(fileName.getBytes(), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
EasyExcel.write(response.getOutputStream(), Export.class)
.autoCloseStream(Boolean.FALSE)
.sheet("导出列表")
.doWrite(list);
} catch (Exception e) {
e.printStackTrace();
}
配置实现
假设我们不想为类上加注解,而是希望在配置/数据库中维护一个Map对象。运行时只需要修改配置/数据库,就可以实现数据导出为excel。
列配置字段:
@Data
public class DownLoadColumnBO {
/**
* 列名(汉字)
*/
private String columnName;
/**
* 字段列
*/
private String columnValue;
/**
* 时间格式化
* 例如:yyyy-MM-dd HH:mm:ss
*/
private String dateFormatter;
/**
* 枚举或者常量,处理列表返回数据,但是却展示汉字
*/
private List<MappingInfo> mappingInfos;
@Data
public static class MappingInfo {
/**
* 文件中的值
*/
private String name;
/**
* 列表中的值
*/
private String value;
}
}
工具类:
@Service
public class DownLoadConvert {
/**
*
* @param datas 数据对象 key-字段名,vlue-字段值
* @param downLoadColumnBOS 下载列的配置(动态读取到配置)
* @return excel的字节流
*/
public byte[] export(List<Map<String, Object>> datas, List<DownLoadColumnBO> downLoadColumnBOS) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ExcelWriter writer = EasyExcelFactory.write(stream).build();
writeExcelAll(writer, datas, downLoadColumnBOS);
writer.finish();
return stream.toByteArray();
}
public void writeExcelAll(ExcelWriter writer, List<Map<String, Object>> datas, List<DownLoadColumnBO> downLoadColumnBOS) {
//数据查询
String sheetName = "sheet";
WriteSheet writeSheet = EasyExcelFactory
.writerSheet(sheetName)
.head(getHeader(downLoadColumnBOS))
.build();
List<List<Object>> objListList = datas.stream()
.map(d -> resolveData(downLoadColumnBOS, d))
.collect(Collectors.toList());
writer.write(objListList, writeSheet);
}
private static <T> List<Object> resolveData(List<DownLoadColumnBO> downLoadColumnBOS, Map<String, Object> data) {
try {
List<Object> objectList = new ArrayList<>();
for (DownLoadColumnBO downLoadColumnBO : downLoadColumnBOS) {
String columnValue = downLoadColumnBO.getColumnValue();
Object o = data.get(columnValue);
if (o == null) {
objectList.add("");
continue;
}
if (StringUtils.isNotBlank(downLoadColumnBO.getDateFormatter())) {
if (o.equals(0L)) {
objectList.add("");
continue;
}
o = new SimpleDateFormat(downLoadColumnBO.getDateFormatter()).format(new Date((long) o));
}
//当配置不为空的时候
if (CollectionUtils.isNotEmpty(downLoadColumnBO.getMappingInfos())) {
Map<String, String> value2Mapping =
downLoadColumnBO.getMappingInfos().stream()
.collect(Collectors.toMap(DownLoadColumnBO.MappingInfo::getValue, DownLoadColumnBO.MappingInfo::getName));
o = value2Mapping.getOrDefault((String) o, (String) o);
}
objectList.add(o);
}
return objectList;
} catch (Exception e) {
return Collections.emptyList();
}
}
private List<List<String>> getHeader(List<DownLoadColumnBO> downLoadColumnBOS) {
//若没有查询到列名
if (CollectionUtils.isEmpty(downLoadColumnBOS)) {
throw new RuntimeException("未配置excel标头");
}
return downLoadColumnBOS.stream().map(DownLoadColumnBO::getColumnName)
.map(Collections::singletonList)
.collect(Collectors.toList());
}
}
网友评论