1. 程式人生 > 其它 >java- excel工具類(EasyPoi)

java- excel工具類(EasyPoi)

excel工具類

EasyPoi

1 匯入依賴
<!--        EasyPoiUtil匯入依賴-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.1.0</version>
        </dependency>

踩坑警告

​ 如果專案中已經有其他excel工具類的依賴了,則把本依賴放到後面,

​ EasyPoiUtil的版本儘量選擇新一些的,避免匯入資料問題

2 工具類
import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.parse.ParseWord07;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * Excel匯入匯出工具類
 */

public class ExcelUtils2 {

    /**
     * excel 匯出
     *
     * @param list     資料列表
     * @param fileName 匯出時的excel名稱
     * @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 fileName 匯出時的excel名稱
     * @param response
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        //把資料新增到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * excel 匯出
     *
     * @param list         資料列表
     * @param pojoClass    pojo型別
     * @param fileName     匯出時的excel名稱
     * @param response
     * @param exportParams 匯出引數(標題、sheet名稱、是否建立表頭,表格型別)
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        //把資料新增到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * excel 匯出
     *
     * @param list         資料列表
     * @param pojoClass    pojo型別
     * @param fileName     匯出時的excel名稱
     * @param exportParams 匯出引數(標題、sheet名稱、是否建立表頭,表格型別)
     * @param response
     */
    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 title     表格內資料標題
     * @param sheetName sheet名稱
     * @param pojoClass pojo型別
     * @param fileName  匯出時的excel名稱
     * @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 title          表格內資料標題
     * @param sheetName      sheet名稱
     * @param pojoClass      pojo型別
     * @param fileName       匯出時的excel名稱
     * @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 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-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } 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 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("/home/server/upload/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       上傳的檔案
     * @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 {
        if (file == null) {
            return null;
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 匯入
     *
     * @param inputStream 檔案輸入流
     * @param titleRows   表格內資料標題行
     * @param headerRows  表頭行
     * @param pojoClass   pojo型別
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/home/server/upload/excel/");
//        params.setNeedSave(true);  //不儲存
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel檔案不能為空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }
}
3 匯入匯出dto
package com.fongtech.cli.mbg.model.dto;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.fongtech.cli.framework.model.BaseModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @Author
 * @Time 2020/11/3 0003
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class CommodityImportDTO  extends BaseModel {
    /**
     * id
     */
    @Excel(name = "id")
    private Integer id;
    /**
     * image
     */
    @Excel(name = "image")
    private String image;
    /**
     * title
     */
    @Excel(name = "title")
    private String title;
    /**
     * asin
     */
    @Excel(name = "asin")
    private String asin;
    /**
     * storeName
     */
    @Excel(name = "storeName")
    private String storeName;
    /**
     * price
     */
    @Excel(name = "price")
    private String price;
    /**
     * currencySymbol
     */
    @Excel(name = "currencySymbol")
    private String currencySymbol;
    /**
     * country
     */
    @Excel(name = "country")
    private String country;

    /**
     * supportedReviewType
     */
    @Excel(name = "supportedReviewType")
    private String supportedReviewType;

    /**
     * startDate
     */
    @Excel(name = "startDate")
    private Date startDate;
    /**
     * endDate
     */
    @Excel(name = "endDate")
    private Date endDate;
    /**
     * dailyTotal
     */
    @Excel(name = "dailyTotal")
    private String dailyTotal;
    /**
     * total
     */
    @Excel(name = "total")
    private String total;
    /**
     * commission
     */
    @Excel(name = "commission")
    private String commission;
    /**
     * url
     */
    @Excel(name = "url")
    private String url;
    /**
     * productSpecification
     */
    @Excel(name = "productSpecification")
    private String productSpecification;
    /**
     * createdTime
     */
    @Excel(name = "createTime")
    private Date createdTime;


}