java
@PostMapping("/exportDHT")
public Response exportDHT(String dateS, String url, HttpServletResponse response) {
Workbook wb = stationFuheService.exportDHT(dateS,url);
try {
response.setContentType("application/octet-stream");
ServletOutputStream os = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("大会堂负荷.xlsx", "utf-8"));
wb.write(os);
os.flush();
os.close();
return Response.success("开关遥控记录导出成功");
} catch (IOException e) {
e.printStackTrace();
return Response.failure("开关遥控记录导出失败");
}
}
实现类
java
@Override
public Workbook exportDHT(String dateS, String url) {
if(ObjectUtil.isEmpty(dateS)){
dateS = DateTimeUtils.getYesterday().concat(","+DateTimeUtils.getToday());
}
List<String> dateList = Arrays.asList(dateS.split(","));
//制作结构
List<String> flowSheet = this.baseMapper.getFlowSheet();
Workbook wb = new XSSFWorkbook();
// 创建表格
Sheet sheet = wb.createSheet("大会堂负荷");
CellStyle cellStyleHead = wb.createCellStyle();
CellStyle cellStyle = wb.createCellStyle();
// 居中
cellStyleHead.setAlignment(HorizontalAlignment.LEFT);
// 设置背景色
cellStyleHead.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
cellStyleHead.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 设置字体大小
Font font = wb.createFont();
font.setFontHeightInPoints((short) 12);
cellStyleHead.setFont(font);
cellStyle.setFont(font);
// 创建标题行
Row row = sheet.createRow(0);
List<String> heads = Arrays.asList("时间,".concat(dateS).split(","));
//列头
for (int j = 0; j < heads.size(); j++) {
sheet.setColumnWidth(j, heads.get(j).getBytes().length * 2 * 300);
Cell cell = row.createCell(j);
cell.setCellStyle(cellStyleHead);
cell.setCellValue(heads.get(j));
}
//第一列固定数据
for (int i = 0; i < flowSheet.size(); i++) {
// 创建行
row = sheet.createRow(i + 1);
// 创建单元格(列号)
row.createCell(0).setCellValue(flowSheet.get(i));
//拓展列数据
for (int k = 0; k < dateList.size(); k++) {
List<FuheVo> list = this.baseMapper.queryStationFuHeByDate(dateList.get(k));
// 创建单元格(列号)
row.createCell(k + 1).setCellValue(list.get(i).getFuhe());
}
}
if(ObjectUtil.isNotEmpty(url)){
byte[] bytes = FileUtils.getImageFromNetByUrl(url);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
CreationHelper helper = wb.getCreationHelper();
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
// 设置图片起始列
anchor.setCol1(4);
// 设置图片起始行
anchor.setRow1(2);
Picture picture = drawing.createPicture(anchor, pictureIdx);
// 调整图片大小
picture.resize();
}
return wb;
}
效果图
需求要求:
注意:前端入参为图像地址,图像是盖在上面,没有指定存储到具体单元格,此方法适用于针对性比较强的需求,对象导入可以用easyExcel更简单.