java导出excel (hutool导出excel)
程序员文章站
2024-03-20 21:13:52
...
maven结构:
依赖包:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.4</version> //或者更新
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version> //或者更新
</dependency>
工具类>>>
//keys>>>T的属性值
//heads>>对应keys顺序的列标题
public static<T> ExcelWriter exportExcel(List<T> list,String[] keys,String[] heads){
Assert.notEmpty(list);
Assert.notEmpty(keys);
Assert.notEmpty(headers);
Assert.checkBetween(keys.length, headers.length, headers.length);
ExcelWriter writer = ExcelUtil.getBigWriter();
for (int i = 0; i < keys.length; i++) {
writer.addHeaderAlias(keys[i], headers[i]);
}
StyleSet style = writer.getStyleSet();
CellStyle cellStyle = style.getCellStyle();
cellStyle.setDataFormat((short) 1);
writer.setStyleSet(style);
writer.setColumnWidth(-1,32);
writer.write(list, isFirst);
ServletOutputStream out = null;
try {
out = response.getOutputStream();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
String fileName = "RefundOrder_"+ DateUtil.format(new Date(), "yyyyMMddHHmmss");
response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
} catch (IOException e) {
e.printStackTrace();
}
writer.flush(out, true); //非流处理无须执行
writer.close(); //执行此步骤算完成导出
IoUtil.close(out); //非流处理无须执行
}
上一篇: UEditor 前后端分离【vue + java版本】
下一篇: Java代码实现Excel表格导出