本文共 2596 字,大约阅读时间需要 8 分钟。
使用EasyExcel完成Excel数据导入与导出
org.apache.poi poi 3.17 org.apache.poi poi-ooxml-schemas 3.17 org.apache.poi poi-ooxml 3.17 com.alibaba easyexcel 2.1.7
| 字段注解 | 类注解 |
|---|---|
| @ColumnWith(列宽) | @ColumnWidth(全局列宽) |
| @ExcelProperty(字段配置) | @HeadFontStyle(头样式) |
| @HeadRowHeight(标题高度) | @ContentFontStyle(内容字体样式) |
| @ContentRowHeight(内容高度) | @ExcelProperty注解 |
value和index只能二选一converter@ExcelProperty(value = "编号", index = 0)private Long id;
@ColumnWidth(value = 255)private String message;
@ContentFontStyle( fontName = "微软雅黑", fontHeightInPoints = 12, italic = true, color = "000000")private String content;
@ContentStyle( dataFormat = "yyyy-MM-dd HH:mm:ss", hidden = false, locked = true)private Date date;
@ContentFontStyle相同的参数@HeadFontStyle( fontName = "微软雅黑", fontHeightInPoints = 14, italic = false)//标题字段private String title;
@ExcelIgnoreprivate ListignoredList;
@Data@ColumnWidth(40)@HeadRowHeight(40)public class OrderExcel { @ExcelProperty(value = "编号", index = 0) private Long id; @ExcelProperty(value = "创建时间", index = 1) @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒") private Date createTime;} public void exportExcel() { List excelList = new ArrayList<>(); // 生成唯一文件名 String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".xlsx"; String filePath = "/path/to/excel/" + fileName; try { // 使用EasyExcel写入Excel EasyExcel.write(filePath, OrderExcel.class) .sheet("订单表") .doWrite(excelList); // 上传到FastDFS FileInputStream fileInputStream = new FileInputStream(new File(filePath)); String uploadedPath = fastDFSClient.upload(fileInputStream, fileName, null); String url = fastDFSDomain + uploadedPath; JSONObject response = new JSONObject(); response.put("url", url); // 删除本地文件 new File(filePath).delete(); } catch (IOException e) { e.printStackTrace(); }} 通过以上方法,您可以轻松完成Excel数据的导入与导出工作。EasyExcel 提供了强大的格式化和样式控制功能,使开发更加简便。
转载地址:http://qmuaz.baihongyu.com/