准備

package com.ps.ande.util; import org.apache.poi.ss.usermodel.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; public class ExportFacade { private static final Logger log = LoggerFactory.getLogger(ExportFacade.class); private static final String ERROR_STR = "導出文件失敗"; public static void setProperties(HttpServletResponse response, String fileName, Workbook workbook, ServletOutputStream outputStream) throws IOException { fileName = new String(fileName.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1); response.setHeader("Content-Disposition", "attachment;filename=" + fileName+".xls"); response.setContentType("application/x-download"); response.setCharacterEncoding("UTF-8"); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); response.flushBuffer(); workbook.write(outputStream); outputStream.flush(); } public static void exportByExcel(HttpServletResponse response, String fileName, Workbook workbook) { try(ServletOutputStream outputStream = response.getOutputStream()) { setProperties(response, fileName, workbook, outputStream); } catch (IOException e) { log.error(ERROR_STR, e); new Exception("導出文件失敗,請重試"); } } }
步驟1
參數說明
title: 標題 ExcelDto: 映射實體類 row: List 集合
映射實體類常用注解maven依賴查看官網 http://easypoi.mydoc.io/
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, ""), ExcelDto.class, row);
步驟2
參數說明
response: HttpServletResponse fileName: 導出文件名稱 workbook: 數據導出處理
ExportFacade.exportByExcel(response, fileName , workbook);
步驟3
數據映射實體類時處理。圖片路徑字段隱藏@ExcelIgnore注解,創建byte[] image 類型字段接收處理的圖片

public byte[] getImage(){ //從流中獲取數據數組。 byte[] b = null; try { if(imageUrl!=null){ //new一個URL對象 URL url = new URL(getImageUrl()); //通過輸入流獲取圖片數據 BufferedImage image = ImageIO.read(url); //得到圖片的二進制數據,以二進制封裝得到數據,具有通用性 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", outStream); b = outStream.toByteArray(); } }catch (Exception e){ throw new YamiShopBindException("圖片處理失敗"); } return b; }
Maven依賴

<!-- Excel導出 --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>4.1.0</version> <exclusions> <exclusion> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>4.1.0</version> <exclusions> <exclusion> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency>