List数据转Excel文件
相关代码如下:
需要注意,转换只支持基本数据类型,不支持List,Map类似的数据结构
实体类
@Data
@TableName("test")
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "A", description = "A")
public class A implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type= IdType.AUTO)
@ExcelProperty(value = "序号主键")
private Integer id;
@ExcelProperty(value = "A")
private String a;
@ColumnWidth(value = 20)
@ExcelProperty(value = "B")
private String b;
@TableField(exist = false)
@ExcelIgnore
private List<UploadVo> c;
@ApiModelProperty(value = "d")
@ExcelProperty(value = "D")
private String d;
@ApiModelProperty(value = "F")
@ExcelProperty(value = "F")
private String f;
}
转换方法
/**
* list数据转excel文件
*
* @param dataList 数据
* @return 文件
*/
public File execFile(List<A> dataList, String fileName, String sheetName) {
String tmpFilePath = "D:\\file\\";
// 如果文件夹不存在则会创建
File f = new File(tmpFilePath);
if (!f.exists()) {
f.mkdirs();
}
File file = new File(tmpFilePath + fileName + System.currentTimeMillis() + ".xlsx");
if (!dataList.isEmpty()) {
//新建ExcelWriter
ExcelWriter excelWriter = EasyExcel.write(file.getAbsoluteFile(), MaterialApplyDetail.class).build();
try {
//获取sheet0对象
// 排除字段 可使用此方式或注解ExcelIgnore
HashSet<String> set0 = new HashSet<>();
//该名称为实体类属性
set0.add("id");
set0.add("a");
set0.add("b");
WriteSheet mainSheet = EasyExcel.writerSheet(0, sheetName).head(MaterialApplyDetail.class).excludeColumnFiledNames(set0).build();
excelWriter.write(dataList, mainSheet);
} catch (Exception e) {
log.error("数据生成excel文件失败,{}", e.getMessage());
} finally {
//关闭流
excelWriter.finish();
}
}
return file;
}