引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
代码实现
Controller
@GetMapping("/exportData")
public void exportData(HttpServletResponse res){
service.exportData(res);
}
Service
@Override
public void exportData(HttpServletResponse res) {
List<BodySignOut> content = listRestApiResultVo.getContent();
try (HSSFWorkbook workbook = new HSSFWorkbook()) {
String fileName = Constants.EXCEL_SIGN_FILENAME;
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell0 = row.createCell(0);
cell0.setCellValue(Constants.EXCEL_SIGN_ID);
XSSFCell cell1 = row.createCell(1);
cell1.setCellValue(Constants.EXCEL_SIGN_TYPE);
XSSFCell cell2 = row.createCell(2);
cell2.setCellValue(Constants.EXCEL_SIGN_VALUE);
XSSFCell cell3 = row.createCell(3);
cell3.setCellValue(Constants.EXCEL_SIGN_DATE);
int rowNum = 1;
for (BodySignOut body : content) {
XSSFRow rowContent = sheet.createRow(rowNum++);
rowContent.createCell(0).setCellValue(body.getId());
rowContent.createCell(1).setCellValue(body.getBodySignType());
rowContent.createCell(2).setCellValue(body.getBodySignValue());
rowContent.createCell(3).setCellValue(body.getPartitionTime());
String filePath = "D:/1/1.jpg";
String fileType = "jpg";
if(StringUtils.isEmpty(filePath) || StringUtils.isEmpty(fileType)){
}
File file = new File(filePath);
if(!file.canRead()){
}
BufferedImage read = ImageIO.read(file);
if (read ==null){
}
ImageIO.write(read,fileType,outputStream);
XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
XSSFCreationHelper creationHelper = workbook.getCreationHelper();
XSSFClientAnchor clientAnchor = creationHelper.createClientAnchor();
clientAnchor.setCol1(4);
clientAnchor.setRow1(i+1);
XSSFPicture picture = drawingPatriarch.createPicture(clientAnchor, workbook.addPicture(outputStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
picture.resize(1,1);
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.flushBuffer();
workbook.write(response.getOutputStream());
} catch (Exception e) {
TdLog.error(Constants.EXCEL_SIGN_ERROR, e);
}
}