1. 程式人生 > >easypoi 一行程式碼搞定excel匯入匯出

easypoi 一行程式碼搞定excel匯入匯出

  • 開發中經常會遇到excel的處理,匯入匯出解析等等,java中比較流行的用poi,但是每次都要寫大段工具類來搞定這事兒,此處推薦一個別人造好的輪子【easypoi】,下面介紹下“輪子”的使用。

pom引入

  • 不再需要其他jar
       <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.3</version>
        </dependency
>
<dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId> <version>3.0.3</version> </dependency>

編寫實體類

  • 此處注意必須要有空建構函式,否則會報錯“物件建立錯誤”
  • 關於註解@Excel,其他還有@ExcelCollection,@ExcelEntity ,@ExcelIgnore,@ExcelTarget等,此處我們用不到,可以去官方檢視更多
屬性型別型別說明
nameStringnull列名
needMergebooleanfasle縱向合併單元格
orderNumString"0"列的排序,支援name_id
replaceString[]{}值得替換 匯出是{a_id,b_id} 匯入反過來
savePathString"upload"匯入檔案儲存路徑
typeint1匯出型別 1 是文字 2 是圖片,3 是函式,10 是數字 預設是文字
widthdouble10列寬
heightdouble10列高,後期打算統一使用@ExcelTarget的height,這個會被廢棄,注意
isStatisticsbooleanfasle自動統計資料,在追加一行統計,把所有資料都和輸出這個處理會吞沒異常,請注意這一點
isHyperlinkbooleanfalse超連結,如果是需要實現介面返回物件
isImportFieldbooleantrue校驗欄位,看看這個欄位是不是匯入的Excel中有,如果沒有說明是錯誤的Excel,讀取失敗,支援name_id
exportFormatString""匯出的時間格式,以這個是否為空來判斷是否需要格式化日期
importFormatString""匯入的時間格式,以這個是否為空來判斷是否需要格式化日期
formatString""時間格式,相當於同時設定了exportFormat 和 importFormat
databaseFormatString"yyyyMMddHHmmss"匯出時間設定,如果欄位是Date型別則不需要設定 資料庫如果是string 型別,這個需要設定這個資料庫格式,用以轉換時間格式輸出
numFormatString""數字格式化,引數是Pattern,使用的物件是DecimalFormat
imageTypeint1匯出型別 1 從file讀取 2 是從資料庫中讀取 預設是檔案 同樣匯入也是一樣的
suffixString""文字字尾,如% 90 變成90%
isWrapbooleantrue是否換行 即支援\n
mergeRelyint[]{}合併單元格依賴關係,比如第二列合併是基於第一列 則{1}就可以了
mergeVerticalbooleanfasle縱向合併內容相同的單元格
import cn.afterturn.easypoi.excel.annotation.Excel;

import java.util.Date;

public class Person {

    @Excel(name = "姓名", orderNum = "0")
    private String name;

    @Excel(name = "性別", replace = {"男_1", "女_2"}, orderNum = "1")
    private String sex;

    @Excel(name = "生日", exportFormat = "yyyy-MM-dd", orderNum = "2")
    private Date birthday;

    public Person(String name, String sex, Date birthday) {
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

匯入匯出公用方法

public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new NormalException(e.getMessage());
        }
    }
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new NormalException("模板不能為空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new NormalException(e.getMessage());
        }
        return list;
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new NormalException("excel檔案不能為空");
        } catch (Exception e) {
            throw new NormalException(e.getMessage());
        }
        return list;
    }

對的,沒看錯,這就可以匯出匯入了,看起來程式碼挺多,其實是提供了多個匯入匯出方法而已

測試

  @RequestMapping("export")
    public void export(HttpServletResponse response){

        //模擬從資料庫獲取需要匯出的資料
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person("路飛","1",new Date());
        Person person2 = new Person("娜美","2", DateUtils.addDate(new Date(),3));
        Person person3 = new Person("索隆","1", DateUtils.addDate(new Date(),10));
        Person person4 = new Person("小狸貓","1", DateUtils.addDate(new Date(),-10));
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        personList.add(person4);

        //匯出操作
        FileUtil.exportExcel(personList,"花名冊","草帽一夥",Person.class,"海賊王.xls",response);
    }

    @RequestMapping("importExcel")
    public void importExcel(){
        String filePath = "F:\\海賊王.xls";
        //解析excel,
        List<Person> personList = FileUtil.importExcel(filePath,1,1,Person.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)匯入
        System.out.println("匯入資料一共【"+personList.size()+"】行");

        //TODO 儲存資料庫
    }

匯出結果

匯出結果

測試匯入

匯出結果再新增一行,執行,輸出匯入資料行數