List<?> list = new ArrayList<>();
if(CollectionUtils.isEmpty(entity.getEntityList())){
Page<?> result = this.findPage(page, entity);
list.addAll(result.getRecords());
}else {
list.addAll(entity.getEntityList());
}
// 初始化导出文件名字
String labelTitle = "***.xlsx";
//设置导出格式
String excelName = new String(labelTitle.getBytes(), StandardCharsets.ISO_8859_1);
// 创建工作簿
XSSFWorkbook excel = new XSSFWorkbook();
// 导出数据
// 创建表头
XSSFSheet sheet = excel.createSheet();
// 此处sheetIndex的参数代表值绘制的第几个sheet页,如果有绘制多个sheet的需求,则0,1,2,3,4……这样创建,不同的sheet页可以复用一个方法或者单独写不同的方法
excel.setSheetName(0, "sheet1");
XSSFCellStyle header = ExcelStyleUtils.genContextStyle(excel);
// 设置sheet名称
XSSFRow tableRow1 = sheet.createRow(0);
// 创建表头样式
XSSFCellStyle tableStyle = ExcelStyleUtils.genTableStyle(excel);
// 组装表头数据
String[] tableTitleInit = {"**", "***", "***", "***", "**"};
for (int i = 0; i < tableTitleInit.length; i++) {
XSSFCell tableRowCell = tableRow1.createCell(i);
tableRowCell.setCellStyle(tableStyle);
tableRowCell.setCellValue(tableTitleInit[i]);
}
// 对以上数据设置自适应宽度
ExcelStyleUtils.setAutoColumnWidth(sheet, 8);
// 主数据内容导出
// 记录行数从表头下方(第四行)开始
int rowNum = 1;
// 创建文本样式
XSSFCellStyle contextStyle = ExcelStyleUtils.genContextStyle(excel);
for (int i = 0; i < list.size(); i++) {
// 创建数据行
XSSFRow tableRow = sheet.createRow(rowNum);
// 取导出数据
AudWarn data = list.get(i);
// 进行逐列单元格塞入数据
for (int j = 0; j < 5; j++) {
XSSFCell rowCell = tableRow.createCell(j);
rowCell.setCellStyle(contextStyle);
switch (j) {
case 0:
rowCell.setCellValue(i + 1);
break;
case 1:
rowCell.setCellValue(data.getId());
break;
case 2:
rowCell.setCellValue(data.getWarnText());
break;
case 3:
rowCell.setCellValue(com.alibaba.excel.util.DateUtils.format(data.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
break;
case 4:
if(data.getStatus() == 0){
rowCell.setCellValue("禁用");
}else {
rowCell.setCellValue("启用");
}
break;
}
}
rowNum++;
}
// 对以上数据设置自适应宽度
ExcelStyleUtils.setAutoColumnWidth(sheet, 8);
// 生成excel文件并入response
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + excelName);
excel.write(response.getOutputStream());
excel.close();
} catch (IOException e) {
e.printStackTrace();
}
JAVA导出excel
Java与Excel在Windows中的应用
最新推荐文章于 2025-12-11 08:58:14 发布
45万+

被折叠的 条评论
为什么被折叠?



