沒想到啊,Java操作Excel竟然這么簡單!
前言
在工作中,使用excel表格處理數(shù)據(jù)是很常見的操作,本文就來講解下如何使用開源輪子實(shí)現(xiàn)下載、導(dǎo)入、導(dǎo)出的功能。
在之前,很多Java程序員都喜歡使用POI的類庫來操作excel,但是非常的不方便,不僅代碼寫的很臃腫,還要處理各種office版本兼容問題,最怕的就是使用不當(dāng)很容易造成內(nèi)存溢出,因此今天給大家推薦阿里的一款開源項(xiàng)目 easyexcel。
項(xiàng)目介紹
easyexcel是一款快速、簡單避免OOM的java處理Excel工具
github地址:https://github.com/alibaba/easyexcel
Start:15.2k
看了下,兩天前項(xiàng)目團(tuán)隊(duì)還有在完善代碼,可見項(xiàng)目還是挺活躍的

項(xiàng)目集成
使用idea開發(fā)工具簡單創(chuàng)建了一個easyexcel-demo項(xiàng)目,加入了web模塊以及easyexcel maven依賴,依賴如下:
????com.alibaba
????easyexcel
????2.2.4
版本的話我們使用2.2.4,2020年6月份上傳的,算是最新的版本了。

好了,我們就開始寫功能了。
1、實(shí)現(xiàn)已有Excel模板下載
很多系統(tǒng)有數(shù)據(jù)批量導(dǎo)入的場景,因?yàn)樵陧撁嫔吓考訑?shù)據(jù)時間成本太大了,但是一般導(dǎo)入的時候得按照一定的格式改,所以一般好的產(chǎn)品會先讓用戶下載一個帶有格式的文檔,然后按照格式寫好以后上傳導(dǎo)入,我們來實(shí)現(xiàn)這個功能吧!
創(chuàng)建模板文件
首先我們創(chuàng)建一個模板文件,內(nèi)容如圖

###將模板文件放置再項(xiàng)目里
然后我們把它放在項(xiàng)目的配置文件下,如圖

然后下載代碼也很簡單,主要分為加載資源->讀取資源->寫入響應(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();
????}
}
測試
啟動項(xiàng)目,訪問,如圖所示,可以下載。

2.寫入數(shù)據(jù)并生成文件
將數(shù)據(jù)導(dǎo)出到文檔這種場景可以說是最常見的了,那么怎么使用easyExcel快速實(shí)現(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?=?"手機(jī)號",?index?=?2)
????private?String?mobile;
????@ExcelProperty(value?=?"性別",?index?=?3)
????private?String?sex;
}
定義這個對象的目的有兩個:當(dāng)前場景下寫入文件作為model對象構(gòu)造數(shù)據(jù)以及下個要講的數(shù)據(jù)讀取了。
「簡要代碼流程如下:」
定義列標(biāo)題->創(chuàng)建sheet->自定義字體和風(fēng)格->構(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?=?{"用戶名","年齡","手機(jī)號","性別"};
????????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ù)

我們再回過頭來看我們定義的這個Model對象,通過指定index可以對應(yīng)讀取的excel里面的列,然后定義的數(shù)據(jù)類型就對應(yīng)到excel里面具體的值,來看看如何實(shí)現(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工具處理的,是不是相當(dāng)簡潔了。對于代碼中的ModelExcelListener,其實(shí)是我們自定義的一個讀取監(jiān)聽類,貼貼代碼:
public?static?class?ModelExcelListener?extends?AnalysisEventListener?{
????????private?List這是一個讀取數(shù)據(jù)監(jiān)聽類,有特殊業(yè)務(wù)需求的都可以在這個類里面自定義實(shí)現(xiàn),比如邊讀邊寫庫啊,數(shù)據(jù)過濾和處理等等,用的好了絕對是一把利劍。
PostMan模擬調(diào)用

控制臺輸出

總結(jié)
通過本篇文章,我們演示了如何使用easyexcel進(jìn)行一些excel的操作,在實(shí)際的項(xiàng)目應(yīng)用中,可以對以上示例代碼進(jìn)行進(jìn)一步的封裝,使其不管是讀取、導(dǎo)出等操作都能幾行代碼搞定,這個就得根據(jù)情況大家自由發(fā)揮了。
項(xiàng)目代碼獲取
地址:https://github.com/pengziliu/GitHub-code-practice/?
點(diǎn)擊底部閱讀原文
已擼完部分開源輪子,更多精彩正在路上
| 模塊 | 所屬開源項(xiàng)目 | 項(xiàng)目介紹 |
|---|---|---|
springboot_api_encryption | rsa-encrypt-body-spring-boot | Spring Boot接口加密,可以對返回值、參數(shù)值通過注解的方式自動加解密 。 |
simpleimage-demo | simpleimage | 圖片處理工具類,具有加水印、壓縮、裁切等功能 |
xxl-job-demo | xxl-job | 分布式定時任務(wù)使用場景 |
xxl-sso-demo | xxl-sso | 單點(diǎn)登錄功能 |
vuepress-demo | vuepress | 建立自己的知識檔案庫 |
xxl-conf-demo | xxl-conf | 分布式配置中心 |
Shardingsphere-demo | Shardingsphere | 分庫分表 |
easyexcel-demo | easyexcel | excel操作工具類 |
