springboot使用easypoi實現導出Excel表格


導入依賴
<!--excel操作-->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>3.3.0</version>
</dependency> 

  

 
@Data
@EqualsAndHashCode(callSuper = false)
public class ProductExportVo implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 商品編號
     */
    @Excel(name = "商品編號", orderNum = "0", width = 15)
    private String productNo;

    /**
     * 商品名稱
     */
    @Excel(name = "商品名稱", orderNum = "1", width = 25)
    private String productName;


    /**
     * 商品類型 
     */
    @Excel(name = "商品類型", orderNum = "2", width = 15)
    private Integer productType;

    /**
     * 面值
     */
    @Excel(name = "面值", orderNum = "3", width = 15)
    private Integer productDeno;

    /**
     * 銷售區域 0 省域 1 市域 2 全國
     */
    @Excel(name = "銷售區域", orderNum = "4", width = 15,replace={"省域_0","市域_1","全國_2"})
    private Integer productSalesArea;

    /**
     * 銷售價
     */
    @Excel(name = "銷售價", orderNum = "5", width = 15)
    private BigDecimal productPrice;

    /**
     * 狀態 0 下架 1 上架
     */
    @Excel(name = "狀態", orderNum = "6", width = 15,replace = {"下架_0","上架_1"})
    private Integer productStatus;

    /**
     * 創建時間
     */
    @Excel(name = "創建時間", orderNum = "7", width = 25)
    private String productCreateTime;

    /**
     * 修改時間
     */
    @Excel(name = "修改時間", orderNum = "8", width = 25)
    private String productModifyTime;
}
定義Vo實體類

 

Excel工具類

public class ExcelUtils {
    /**
     * excel 導出
     *
     * @param list           數據
     * @param title          標題
     * @param sheetName      sheet名稱
     * @param pojoClass      pojo類型
     * @param fileName       文件名稱
     * @param isCreateHeader 是否創建表頭
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 導出
     *
     * @param list      數據
     * @param title     標題
     * @param sheetName sheet名稱
     * @param pojoClass pojo類型
     * @param fileName  文件名稱
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
    }

    /**
     * excel 導出
     *
     * @param list         數據
     * @param pojoClass    pojo類型
     * @param fileName     文件名稱
     * @param response
     * @param exportParams 導出參數
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 導出
     *
     * @param list     數據
     * @param fileName 文件名稱
     * @param response
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, fileName, response);
    }

    /**
     * 默認的 excel 導出
     *
     * @param list         數據
     * @param pojoClass    pojo類型
     * @param fileName     文件名稱
     * @param response
     * @param exportParams 導出參數
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 默認的 excel 導出
     *
     * @param list     數據
     * @param fileName 文件名稱
     * @param response
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 下載
     *
     * @param fileName 文件名稱
     * @param response
     * @param workbook excel數據
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
//            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("content-Type", "multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLS.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 導入
     *
     * @param filePath   excel文件路徑
     * @param titleRows  標題行
     * @param headerRows 表頭行
     * @param pojoClass  pojo類型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setNeedSave(true);
        params.setSaveUrl("/excel/");
        try {
            return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("模板不能為空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 導入
     *
     * @param file      excel文件
     * @param pojoClass pojo類型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
        return importExcel(file, 1, 1, pojoClass);
    }

    /**
     * excel 導入
     *
     * @param file       excel文件
     * @param titleRows  標題行
     * @param headerRows 表頭行
     * @param pojoClass  pojo類型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        return importExcel(file, titleRows, headerRows, false, pojoClass);
    }

    /**
     * excel 導入
     *
     * @param file       上傳的文件
     * @param titleRows  標題行
     * @param headerRows 表頭行
     * @param needVerfiy 是否檢驗excel內容
     * @param pojoClass  pojo類型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
        if (file == null) {
            return null;
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 導入
     *
     * @param inputStream 文件輸入流
     * @param titleRows   標題行
     * @param headerRows  表頭行
     * @param needVerfiy  是否檢驗excel內容
     * @param pojoClass   pojo類型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        params.setNeedVerfiy(needVerfiy);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能為空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * Excel 類型枚舉
     */
    enum ExcelTypeEnum {
        XLS("xls"), XLSX("xlsx");
        private String value;

        ExcelTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
ExcelUtil

 

  

控制層

@PostMapping("products/exportAsExcel")
public void exportAsExcel(HttpServletResponse response,ProductSearchDto productSearchDto) {
    final String name = SecurityContextHolder.getContext().getAuthentication().getName();
    log.info("用戶[{}, {}]查導出商品表", name, request.getRemoteAddr());
    if (productSearchDto.getProductDenoRange() != null && productSearchDto.getProductDenoRange().length < 2) {
        productSearchDto.setProductDenoRange(null);
    }
    if (productSearchDto.getProductPriceRange() != null && productSearchDto.getProductPriceRange().length < 2) {
        productSearchDto.setProductPriceRange(null);
    }
     List<ProductExportVo> productList = productService.queryProduct(productSearchDto);
    try {
        ExcelUtils.exportExcel(productList,"商品信息表","商品信息",ProductExportVo.class,"商品信息",response);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

  

前端Vue

downLoad(parmas) {
      var temp = document.createElement("form");
      temp.action = `/api/products/exportAsExcel?${qs.stringify(parmas)}`;
      temp.method = "post";
      temp.style.display = "none";
      document.body.appendChild(temp);
      temp.submit();
    },

  更多Easypoi 用法參考文檔:http://easypoi.mydoc.io/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM