java poi excel 导出
(导出excel 文字+图片流传入)
思路:流传入图片 解析进行单元格填充
入口:
@PostMapping(value = "/exportDIY")
@ResponseBody
@ApiOperation("多格式导出")
@ControllerLog(description = "多格式导出", logLevel = 6)
public ResponseResult exportDIY(HttpServletResponse response, @RequestBody Map<String, String> request) {
return logService.exportDIY(response, request);
}
主要:
OutputStream out = null;
try {
out = response.getOutputStream();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("log_view");
// 表头
int i = setExcelTitleMsg(request, (HSSFWorkbook) wb, sheet);
//创建绘图
String dataChartString1 = URLDecoder.decode(request.get("image1").substring(22), "UTF-8").replaceAll(" ", "+");
String dataChartString2 = URLDecoder.decode(request.get("image2").substring(22), "UTF-8").replaceAll(" ", "+");
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
BASE64Decoder base64Decoder = new BASE64Decoder();
ByteArrayOutputStream dataChartStringoutStream = new ByteArrayOutputStream();
ByteArrayInputStream dataChartStringin = new ByteArrayInputStream(base64Decoder.decodeBuffer(dataChartString1)); //将picInfoByte作为输入流;
BufferedImage dataChartStringbufferImg = ImageIO.read(dataChartStringin); //将dataChartStringin作为输入流,读取图片存入image中
ImageIO.write(dataChartStringbufferImg, "png", dataChartStringoutStream); // 利用HSSFPatriarch将图片写入EXCEL
// 左上角第一列,第几行,右上角第几列,第几行
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 100, 100, (short) 2, i + 1, (short) 8, i + 12);
anchor.setAnchorType(ClientAnchor.AnchorType.byId(3));
patriarch.createPicture(anchor, wb.addPicture(dataChartStringoutStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
ByteArrayOutputStream dataChartStringoutStream2 = new ByteArrayOutputStream();
ByteArrayInputStream dataChartStringin2 = new ByteArrayInputStream(base64Decoder.decodeBuffer(dataChartString2)); //将picInfoByte作为输入流;
BufferedImage dataChartStringbufferImg2 = ImageIO.read(dataChartStringin2); //将dataChartStringin作为输入流,读取图片存入image中
ImageIO.write(dataChartStringbufferImg2, "png", dataChartStringoutStream2);
HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 100, 100, (short) 9, i + 1, (short) 15, i + 12);
anchor.setAnchorType(ClientAnchor.AnchorType.byId(3));
patriarch.createPicture(anchor2, wb.addPicture(dataChartStringoutStream2.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
response.setContentType("application/excel");
response.addHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes("gb2312"), "ISO8859-1"));
wb.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上脱坑位置:
String dataChartString1 = URLDecoder.decode(request.get("image1").substring(22), "UTF-8").replaceAll(" ", "+");
截取前面位置,避免图片写入乱码!
参考来自:https://blog.csdn.net/qq_38130280/article/details/89486068
postman自测OK,导出结果: