1. 程式人生 > 實用技巧 >easypoi 匯入匯出

easypoi 匯入匯出

這次任務是報表的匯入匯出,總結一下心得。

1 匯入依賴 專案原本就有

2 接下來就是使用,用起來也是很簡單。一切查詢資料都是按照正常邏輯來寫。

  匯出:

1 圖片

/**
     * oe下載
     * @param
     * @param response
     * ExcelExportUtil.exportExcel
     */
    @RequestMapping("OeDecodingExcelExport")
    @ResponseBody
    public Result OeDecodingExcelExport(HttpServletResponse response,String startTime,String endTime,Integer logoCode) throws
IOException { Result result=new Result(); response.setContentType("text/html; charset=utf-8"); //查詢資料 List<OeDecoding> oeDecoding = iOeDecoding.oeCodeExcelExport(startTime,endTime,logoCode); if(oeDecoding.size()==0){ result.setResultCode(new ResultCode(-1,"無資料,請重新選擇"));
return result; } Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("oe碼解碼", "oe碼解碼", ExcelType.XSSF), OeDecoding.class, oeDecoding); String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HHmmss")); fileName += fileName + "oe碼解碼"; fileName
= URLEncoder.encode(fileName, "UTF-8"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); workbook.write(response.getOutputStream()); return result; }

核心方法:

 Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("oe碼解碼", "oe碼解碼", ExcelType.XSSF),
                OeDecoding.class, oeDecoding);

解釋:

第一個引數是title名字,第二個是sheetname名字,ExcelType.XSSF 是固定格式,“OeDecoding.class”,這個是實體類的對映這是主要點。oeDecoding,這個是需要下載的資料,如果只是下載固定模板的話,這個就不要了。

2 實體類方法註解

@excel 註解打上就可以實現下載了。還有不同的屬性值可以設定,這裡可以去看官方文件。

    匯入:

核心方法:

ExcelImportResult<OeDecoding> list = ExcelImportUtil.importExcelMore(file.getInputStream(), OeDecoding.class, params);
ExcelImportUtil,提供了很多方法,可以進原始檔看看。這個不需要些,引入依賴就有了。
我摘了原始檔:
/**
 * Copyright 2013-2015 JueYue ([email protected])
 *   
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.afterturn.easypoi.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import cn.afterturn.easypoi.handler.inter.IReadHandler;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.excel.imports.ExcelImportService;
import cn.afterturn.easypoi.excel.imports.sax.SaxReadExcel;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;

/**
 * Excel 匯入工具
 * 
 * @author JueYue
 *  2013-9-24
 * @version 1.0
 */
@SuppressWarnings({ "unchecked" })
public class ExcelImportUtil {

    private ExcelImportUtil() {
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelImportUtil.class);

    /**
     * Excel 匯入 資料來源本地檔案,不返回校驗結果 匯入 字 段型別 Integer,Long,Double,Date,String,Boolean
     * 
     * @param file
     * @param pojoClass
     * @param params
     * @return
     */
    public static <T> List<T> importExcel(File file, Class<?> pojoClass, ImportParams params) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            return new ExcelImportService().importExcelByIs(in, pojoClass, params, false).getList();
        } catch (ExcelImportException e) {
            throw new ExcelImportException(e.getType(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new ExcelImportException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * Excel 匯入 資料來源IO流,不返回校驗結果 匯入 欄位型別 Integer,Long,Double,Date,String,Boolean
     * 
     * @param inputstream
     * @param pojoClass
     * @param params
     * @return
     * @throws Exception
     */
    public static <T> List<T> importExcel(InputStream inputstream, Class<?> pojoClass,
                                          ImportParams params) throws Exception {
        return new ExcelImportService().importExcelByIs(inputstream, pojoClass, params, false).getList();
    }

    /**
     * Excel 匯入 資料來源IO流 欄位型別 Integer,Long,Double,Date,String,Boolean
     * 支援校驗,支援Key-Value
     * 
     * @param inputstream
     * @param pojoClass
     * @param params
     * @return
     * @throws Exception
     */
    public static <T> ExcelImportResult<T> importExcelMore(InputStream inputstream,
                                                             Class<?> pojoClass,
                                                             ImportParams params) throws Exception {
        return new ExcelImportService().importExcelByIs(inputstream, pojoClass, params, true);
    }

    /**
     * Excel 匯入 資料來源本地檔案 欄位型別 Integer,Long,Double,Date,String,Boolean
     * 支援校驗,支援Key-Value
     * @param file
     * @param pojoClass
     * @param params
     * @return
     */
    public static <T> ExcelImportResult<T> importExcelMore(File file, Class<?> pojoClass,
                                                             ImportParams params) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            return new ExcelImportService().importExcelByIs(in, pojoClass, params, true);
        } catch (ExcelImportException e) {
            throw new ExcelImportException(e.getType(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new ExcelImportException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * Excel 通過SAX解析方法,適合大資料匯入,不支援圖片
     * 匯入 資料來源本地檔案,不返回校驗結果 匯入 字 段型別 Integer,Long,Double,Date,String,Boolean
     * 
     * @param inputstream
     * @param pojoClass
     * @param params
     * @param handler
     */
    public static void importExcelBySax(InputStream inputstream, Class<?> pojoClass,
                                        ImportParams params, IReadHandler handler) {
        new SaxReadExcel().readExcel(inputstream, pojoClass, params, handler);
    }

}

不同的方法對應的引數也不同,請對著自己的需求,選擇方法。

總之,方法是很簡答的。但是我的需求對上傳的資料篩選條件有點多,這裡就不放出來了。只是提供一種思路。