EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。
github地址: https://github.com/alibaba/easyexcel
官方文档: https://www.yuque.com/easyexcel/doc/easyexcel
1.引入EasyExcel相关依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
</dependencies>
2.Impl
public void exportFileUploadLog(HttpServletResponse response) throws IOException {
List<CdaFileUploadLogEntity> cdaFileUploadLogEntityList = cdaFileUploadLogEntityMapper.selectList(null);
System.out.println(cdaFileUploadLogEntityList);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置 水平居中
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 必填参数,所以需要声明
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
// 以response方式下载excel表格
response.setHeader("Content-Disposition", "attachment; filename=CdaFileUploadLog.xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 操作excel表写入数据
EasyExcel.write(response.getOutputStream(),CdaFileUploadLogEntity.class)
.registerWriteHandler(horizontalCellStyleStrategy)
.sheet("上传文件历史记录")
.doWrite(cdaFileUploadLogEntityList);
}
Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("文件上传日志")
@TableName("file_upload_log")
public class CdaFileUploadLogEntity implements Serializable {
private Long trnKey;
@ApiModelProperty("文件名")
private String uploadFileName;
@ApiModelProperty("文件类型")
private String uploadFileType;
@ApiModelProperty("上传时间")
// @TableField(fill = FieldFill.INSERT)
private Date uploadFileDatetime;
@ApiModelProperty("上传人")
private String uploadUserName;
@ApiModelProperty("s3key")
private String uploadS3key;
@ApiModelProperty("server")
private String server;
@TableField(exist = false)
private String fileTypeChinese;
}