1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        沒想到啊,Java操作Excel竟然這么簡單!

        共 3199字,需瀏覽 7分鐘

         ·

        2021-02-05 16:17

        前言

        在工作中,使用excel表格處理數(shù)據(jù)是很常見的操作,本文就來講解下如何使用開源輪子實現(xiàn)下載、導(dǎo)入、導(dǎo)出的功能。

        在之前,很多Java程序員都喜歡使用POI的類庫來操作excel,但是非常的不方便,不僅代碼寫的很臃腫,還要處理各種office版本兼容問題,最怕的就是使用不當很容易造成內(nèi)存溢出,因此今天給大家推薦阿里的一款開源項目 easyexcel。

        項目介紹

        easyexcel是一款快速、簡單避免OOM的java處理Excel工具

        github地址:https://github.com/alibaba/easyexcel

        Start:15.2k

        看了下,兩天前項目團隊還有在完善代碼,可見項目還是挺活躍的

        image-20200611173444558

        項目集成

        使用idea開發(fā)工具簡單創(chuàng)建了一個easyexcel-demo項目,加入了web模塊以及easyexcel maven依賴,依賴如下:



        ????com.alibaba
        ????easyexcel
        ????2.2.4


        版本的話我們使用2.2.4,2020年6月份上傳的,算是最新的版本了。

        image-20200611174114531

        好了,我們就開始寫功能了。

        1、實現(xiàn)已有Excel模板下載

        很多系統(tǒng)有數(shù)據(jù)批量導(dǎo)入的場景,因為在頁面上批量加數(shù)據(jù)時間成本太大了,但是一般導(dǎo)入的時候得按照一定的格式改,所以一般好的產(chǎn)品會先讓用戶下載一個帶有格式的文檔,然后按照格式寫好以后上傳導(dǎo)入,我們來實現(xiàn)這個功能吧!

        創(chuàng)建模板文件

        首先我們創(chuàng)建一個模板文件,內(nèi)容如圖

        image-20200611175645484

        ###將模板文件放置再項目里

        然后我們把它放在項目的配置文件下,如圖

        image-20200611184415028

        然后下載代碼也很簡單,主要分為加載資源->讀取資源->寫入響應(yīng)流

        @RestController
        @RequestMapping("/user")
        public?class?UserController?{
        ????/**
        ?????*?下載模板
        ?????*/

        ????@GetMapping("/downloadTemplate")
        ????public?void?downloadTemplate(HttpServletResponse?response)?throws?Exception?{
        ????????ClassPathResource?classPathResource?=?new?ClassPathResource("excelTemplate/easyexcel.xlsx");
        ????????InputStream?inputStream?=?classPathResource.getInputStream();
        ????????Workbook?workbook?=?new?HSSFWorkbook(inputStream);
        ????????response.setContentType("application/vnd.ms-excel");
        ????????response.setHeader("content-Disposition",?"attachment;filename="?+?URLEncoder.encode("easyexcel.xlsx",?"utf-8"));
        ????????response.setHeader("Access-Control-Expose-Headers",?"content-Disposition");
        ????????OutputStream?outputStream?=?response.getOutputStream();
        ????????workbook.write(outputStream);
        ????????outputStream.flush();
        ????????outputStream.close();
        ????}
        }

        測試

        啟動項目,訪問,如圖所示,可以下載。

        Jun-11-2020 18-41-52

        2.寫入數(shù)據(jù)并生成文件

        將數(shù)據(jù)導(dǎo)出到文檔這種場景可以說是最常見的了,那么怎么使用easyExcel快速實現(xiàn)呢,我們同樣還是以上面的模板為例

        定義模型映射對象 UserExcelModel

        @Data
        public?class?UserExcelModel??extends?BaseRowModel?implements?Serializable?{

        ????@ExcelProperty(value?=?"用戶名",?index?=?0)
        ????private?String?name;

        ????@ExcelProperty(value?=?"年齡",?index?=?1)
        ????private?Integer?age;

        ????@ExcelProperty(value?=?"手機號",?index?=?2)
        ????private?String?mobile;

        ????@ExcelProperty(value?=?"性別",?index?=?3)
        ????private?String?sex;
        }

        定義這個對象的目的有兩個:當前場景下寫入文件作為model對象構(gòu)造數(shù)據(jù)以及下個要講的數(shù)據(jù)讀取了。

        「簡要代碼流程如下:」

        定義列標題->創(chuàng)建sheet->自定義字體和風格->構(gòu)造數(shù)據(jù)->寫入數(shù)據(jù)->寫入到瀏覽器響應(yīng)流

        ?/**
        ?????*?導(dǎo)出數(shù)據(jù)
        ?????*/

        ????@GetMapping("/exportData")
        ????public?void?exportData(HttpServletResponse?response)?throws?Exception?{
        ????????XSSFWorkbook?workbook?=?new?XSSFWorkbook();

        ????????String?[]columnNames?=?{"用戶名","年齡","手機號","性別"};

        ????????Sheet?sheet?=?workbook.createSheet();
        ????????Font?titleFont?=?workbook.createFont();
        ????????titleFont.setFontName("simsun");
        ????????titleFont.setBold(true);
        ????????titleFont.setColor(IndexedColors.BLACK.index);

        ????????XSSFCellStyle?titleStyle?=?workbook.createCellStyle();
        ????????titleStyle.setAlignment(HorizontalAlignment.CENTER);
        ????????titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        ????????titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        ????????titleStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        ????????titleStyle.setFont(titleFont);

        ????????Row?titleRow?=?sheet.createRow(0);

        ????????for?(int?i?=?0;?i?????????????Cell?cell?=?titleRow.createCell(i);
        ????????????cell.setCellValue(columnNames[i]);
        ????????????cell.setCellStyle(titleStyle);
        ????????}
        ????????//模擬構(gòu)造數(shù)據(jù)
        ????????List?dataList?=?new?ArrayList<>();
        ????????dataList.add(new?UserExcelModel("張三",12,"13867098765","男"));
        ????????dataList.add(new?UserExcelModel("張三1",12,"13867098765","男"));
        ????????dataList.add(new?UserExcelModel("張三2",12,"13867098765","男"));
        ????????dataList.add(new?UserExcelModel("張三3",12,"13867098765","男"));

        ????????//創(chuàng)建數(shù)據(jù)行并寫入值
        ????????for?(int?j?=?0;?j?????????????UserExcelModel?userExcelModel?=?dataList.get(j);
        ????????????int?lastRowNum?=?sheet.getLastRowNum();
        ????????????Row?dataRow?=?sheet.createRow(lastRowNum?+?1);
        ????????????dataRow.createCell(0).setCellValue(userExcelModel.getName());
        ????????????dataRow.createCell(1).setCellValue(userExcelModel.getAge());
        ????????????dataRow.createCell(2).setCellValue(userExcelModel.getMobile());
        ????????????dataRow.createCell(3).setCellValue(userExcelModel.getSex());
        ????????}
        ????????response.setContentType("application/vnd.ms-excel");
        ????????response.setHeader("content-Disposition",?"attachment;filename="?+?URLEncoder.encode("easyexcel.xls",?"utf-8"));
        ????????response.setHeader("Access-Control-Expose-Headers",?"content-Disposition");
        ????????OutputStream?outputStream?=?response.getOutputStream();
        ????????workbook.write(outputStream);
        ????????outputStream.flush();
        ????????outputStream.close();
        ????}


        3.讀取數(shù)據(jù)

        image-20200619140427117

        我們再回過頭來看我們定義的這個Model對象,通過指定index可以對應(yīng)讀取的excel里面的列,然后定義的數(shù)據(jù)類型就對應(yīng)到excel里面具體的值,來看看如何實現(xiàn):

        ????@PostMapping("/readExcel")
        ????public?List?readExcel(@RequestParam("file")?MultipartFile?file){
        ????????List?list?=?new?ArrayList<>();
        ????????try?{
        ????????????list?=?EasyExcel.read(file.getInputStream(),UserExcelModel.class,new?ModelExcelListener()).sheet().doReadSync();
        ????????}?catch?(IOException?e)?{
        ????????????e.printStackTrace();
        ????????}
        ????????return?list;
        ????}

        看完代碼是不是心里一萬頭草擬嗎飛過~ 看完這個代碼再看用poi工具處理的,是不是相當簡潔了。對于代碼中的ModelExcelListener,其實是我們自定義的一個讀取監(jiān)聽類,貼貼代碼:

        public?static?class?ModelExcelListener?extends?AnalysisEventListener?{
        ????????private?List?datas?=?new?ArrayList<>();
        ????????/**
        ?????????*?通過?AnalysisContext?對象還可以獲取當前?sheet,當前行等數(shù)據(jù)
        ?????????*/

        ????????@Override
        ????????public?void?invoke(Object?data,?AnalysisContext?context)?{
        ????????????//數(shù)據(jù)存儲到list,供批量處理,或后續(xù)自己業(yè)務(wù)邏輯處理。
        ????????????log.info("讀取到數(shù)據(jù){}",data);
        ????????????datas.add(data);
        ????????????//根據(jù)業(yè)務(wù)自行處理,可以寫入數(shù)據(jù)庫等等
        ????????}

        ????????//所以的數(shù)據(jù)解析完了調(diào)用
        ????????@Override
        ????????public?void?doAfterAllAnalysed(AnalysisContext?context)?{
        ????????????log.info("所有數(shù)據(jù)解析完成");
        ????????}
        ????}

        這是一個讀取數(shù)據(jù)監(jiān)聽類,有特殊業(yè)務(wù)需求的都可以在這個類里面自定義實現(xiàn),比如邊讀邊寫庫啊,數(shù)據(jù)過濾和處理等等,用的好了絕對是一把利劍。

        PostMan模擬調(diào)用

        image-20200619145720559

        控制臺輸出

        image-20200619145829105

        總結(jié)

        通過本篇文章,我們演示了如何使用easyexcel進行一些excel的操作,在實際的項目應(yīng)用中,可以對以上示例代碼進行進一步的封裝,使其不管是讀取、導(dǎo)出等操作都能幾行代碼搞定,這個就得根據(jù)情況大家自由發(fā)揮了。

        項目代碼獲取

        1. 地址:https://github.com/pengziliu/GitHub-code-practice/?

        2. 點擊底部閱讀原文


        已擼完部分開源輪子,更多精彩正在路上

        模塊所屬開源項目項目介紹
        springboot_api_encryptionrsa-encrypt-body-spring-bootSpring Boot接口加密,可以對返回值、參數(shù)值通過注解的方式自動加解密 。
        simpleimage-demosimpleimage圖片處理工具類,具有加水印、壓縮、裁切等功能
        xxl-job-demoxxl-job分布式定時任務(wù)使用場景
        xxl-sso-demoxxl-sso單點登錄功能
        vuepress-demovuepress建立自己的知識檔案庫
        xxl-conf-demoxxl-conf分布式配置中心
        Shardingsphere-demoShardingsphere分庫分表
        easyexcel-demoeasyexcelexcel操作工具類

        喜歡做關(guān)注做個標記唄。點個再看,發(fā)文第一時間知道~

        瀏覽 44
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

          <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            日韩中文字幕有码 | 国产精品超碰 | 欧美一区二区鲁丝袜片 | 亚洲乱伦色视频 | 欧美成人在线视频 | 影音先锋琪琪 | 国产午夜精品久久久久 | 色老头吮她的花蒂视频 | 老鸭窝毛片 | 色五月天综合 |