使用EasyPoi快速實(shí)現(xiàn)Excel的導(dǎo)入導(dǎo)出

excel.jpg

近期完成了后管系統(tǒng)報(bào)表的導(dǎo)入導(dǎo)出藻烤,完成之后做下總結(jié)

1绷雏、首先我們對(duì)采用的插件進(jìn)行了篩選,最后選擇EasyPoi怖亭,用的人也很多涎显,算是對(duì)poi的簡(jiǎn)單封裝

這里項(xiàng)目用的springboot,所以只用pom引入配置即可

        <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>

2兴猩、根據(jù)配置編寫(xiě)實(shí)體類(lèi)

先簡(jiǎn)單介紹一下關(guān)于@Excel注解的一些常用屬性
name:列名
orderNum:第幾列
replace:值得替換 例:replace = {"身份證_1"} 數(shù)據(jù)庫(kù)值為"1"期吓,導(dǎo)出時(shí)會(huì)自動(dòng)被"身份證"代替

    @Excel(name = "姓名", orderNum = "0")
    private String name;
    @Excel(name = "證件類(lèi)型", replace = {"身份證_1"}, orderNum = "1")
    private String identifyType;
    @Excel(name = "證件號(hào)碼", orderNum = "2")
    private String identifyNo;
    @Excel(name = "手機(jī)號(hào)1", orderNum = "3")
    private String phoneA;
    @Excel(name = "手機(jī)號(hào)2", orderNum = "4")
    private String phoneB;
    @Excel(name = "手機(jī)號(hào)3", orderNum = "5")
    private String phoneC;
    @Excel(name = "固定電話", orderNum = "6")
    private String telephone;
    @Excel(name = "電子郵箱", orderNum = "7")
    private String email;
    @Excel(name = "身份證地址", orderNum = "8")
    private String idcardAdress;
    @Excel(name = "戶籍地址", orderNum = "9")
    private String householdAddress;
    @Excel(name = "居住地址", orderNum = "10")
    private String liveAddress;
    @Excel(name = "工作地址", orderNum = "11")
    private String workAddress;

3、整合導(dǎo)入導(dǎo)出方法

package com.***.common;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

public class FileWithExcelUtil {
    private static final Logger log = LoggerFactory.getLogger(FileWithExcelUtil .class);
    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) {
            log.error("[monitor][IO][表單功能]", e);
        }
    }
    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 e;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        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 e;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[monitor][表單功能]", e);
        }
        return list;
    }

}

4倾芝、導(dǎo)出操作

/**
     * 導(dǎo)出模版
     * @param response
     */
    @RequestMapping("/exportExcel/model")
    public ResponseModel export(HttpServletResponse response){
       try {
            //模擬從數(shù)據(jù)庫(kù)獲取需要導(dǎo)出的數(shù)據(jù)
            List<CustomerList> personList = new ArrayList<>();
            FileWithExcelUtil.exportExcel(personList,"客戶信息表","客戶表",CustomerList.class,"客戶表.xls",response);
            return ResponseModel.success("操作成功");
        } catch (Exception e) {
            logger.info("getCustomerPage", e);
            return ResponseModel.fail("導(dǎo)出模版失敗");
            // TODO: handle exception
        }
      
    }

5讨勤、導(dǎo)入操作

將導(dǎo)入的模版數(shù)據(jù)拿到,填充到自己要使用的實(shí)體類(lèi)
ps:導(dǎo)入的數(shù)據(jù)模版一般都是平鋪的晨另,而我們的實(shí)體類(lèi)一般都有層次潭千,所以我們的excel模版實(shí)體往往不是我們數(shù)據(jù)庫(kù)對(duì)應(yīng)的bean,需要我們將其自行填充

/**
     * 導(dǎo)入excel
     */
    @RequestMapping(value = "/importExcelForType", method = RequestMethod.POST)
    public ResponseModel importExcel(@RequestParam("file") MultipartFile file,String customerType){
        try {
//          String filePath = "/Users/***/Downloads/response.xls";
            //解析excel借尿,
//          List<CustomerList> personList = FileWithExcelUtil.importExcel(filePath, 1, 1, CustomerList.class);
            List<CustomerList> personList = FileWithExcelUtil.importExcel(file, 1, 1, CustomerList.class);
            //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)導(dǎo)入
            System.out.println("導(dǎo)入數(shù)據(jù)一共【"+personList.size()+"】行");
            
            for (int i = 0; i < personList.size(); i++) {
                CustomerList excel = personList.get(i);
                CmCustomerForExcel customer =  customerListByExcel(excel);
                customer.setCustomerType(customerType);
                customerService.saveExcelList(customer);
            }
            logger.info(personList.toString());
            return ResponseModel.success("操作成功");
            
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.toString());
            return ResponseModel.fail("導(dǎo)入失敗");
        }
    

補(bǔ)充

高級(jí)用法可參考EasyPoi的官方文檔:http://easypoi.mydoc.io

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末刨晴,一起剝皮案震驚了整個(gè)濱河市屉来,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌狈癞,老刑警劉巖茄靠,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異蝶桶,居然都是意外死亡慨绳,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)真竖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)脐雪,“玉大人,你說(shuō)我怎么就攤上這事疼邀∥菇” “怎么了召锈?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵旁振,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我涨岁,道長(zhǎng)拐袜,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任梢薪,我火速辦了婚禮蹬铺,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘秉撇。我一直安慰自己甜攀,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布琐馆。 她就那樣靜靜地躺著规阀,像睡著了一般。 火紅的嫁衣襯著肌膚如雪瘦麸。 梳的紋絲不亂的頭發(fā)上谁撼,一...
    開(kāi)封第一講書(shū)人閱讀 51,125評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音滋饲,去河邊找鬼厉碟。 笑死,一個(gè)胖子當(dāng)著我的面吹牛屠缭,可吹牛的內(nèi)容都是我干的箍鼓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼呵曹,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼袄秩!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤之剧,失蹤者是張志新(化名)和其女友劉穎郭卫,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體背稼,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡贰军,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蟹肘。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片词疼。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖帘腹,靈堂內(nèi)的尸體忽然破棺而出贰盗,到底是詐尸還是另有隱情,我是刑警寧澤阳欲,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布舵盈,位于F島的核電站,受9級(jí)特大地震影響球化,放射性物質(zhì)發(fā)生泄漏秽晚。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一筒愚、第九天 我趴在偏房一處隱蔽的房頂上張望赴蝇。 院中可真熱鬧,春花似錦巢掺、人聲如沸句伶。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)考余。三九已至,卻和暖如春倔约,著一層夾襖步出監(jiān)牢的瞬間秃殉,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工浸剩, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留钾军,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓绢要,卻偏偏與公主長(zhǎng)得像吏恭,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子重罪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353