java操作Excel兩種方式EasyExcel 和POI

一、POI

1.引入依賴

<!-- 03 xls-->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.9</version>
</dependency><!-- 07 xlsx -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.9</version>
</dependency><!-- 日期格式化 -->
<dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.10.4</version>
</dependency>

2.讀取Excel

package com.example;import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;import java.io.*;public class Test {public static void main(String[] args) throws Exception {//獲取文件的數據流InputStream inputStream = new FileInputStream("D:\\java\\測試.xls");//創建文件對象Workbook workbook = new HSSFWorkbook(inputStream);//獲取SheetSheet sheet = workbook.getSheetAt(0);//獲取行Row row = sheet.getRow(0);//獲取列Cell cell = row.getCell(0);String stringCellValue = cell.getStringCellValue();System.out.println(stringCellValue);inputStream.close();}
}

3.寫入Excel

package com.example;import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;import java.io.*;public class Test {public static void main(String[] args) throws Exception {//獲取文件的數據流InputStream inputStream = new FileInputStream("D:\\java\\demo.xls");//創建文件對象Workbook workbook = new HSSFWorkbook(inputStream);//獲取SheetSheet sheet = workbook.getSheetAt(0);int rows = sheet.getPhysicalNumberOfRows();for (int i = 0; i < rows; i++) {Row row = sheet.getRow(i);int cells = row.getPhysicalNumberOfCells();for (int j = 0; j < cells; j++) {Cell cell = row.getCell(j);int type = cell.getCellType();String value = "";switch (type){case HSSFCell.CELL_TYPE_STRING:value = cell.getStringCellValue();break;case HSSFCell.CELL_TYPE_NUMERIC:cell.setCellType(HSSFCell.CELL_TYPE_STRING);value = cell.getStringCellValue();break;}System.out.print(value+" ");}System.out.println();}inputStream.close();}
}

二、EasyExcel

EasyExcel 會將 Excel 數據和 Java 對象之間綁定起來

1.引入依賴

<!-- EasyExcel -->
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version>
</dependency>

2.創建跟 Excel 數據格式對應的 Java 類

package com.example;import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;import java.util.Date;@Data
public class ExcelVO {@ExcelProperty("ID")private Integer id;@ExcelProperty("公司名稱")private String name;@ExcelProperty("停車場")private String park;@ExcelProperty("車牌號")private String number;@ExcelProperty("支付類別")private String type;@ExcelProperty("支付金額(元)")private Integer money;@ExcelProperty("支付時間")private Date time;
}

3.讀取數據

package com.example;import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;import java.io.*;public class Test {public static void main(String[] args) throws Exception {InputStream inputStream = new FileInputStream("D:\\java\\demo.xls");EasyExcel.read(inputStream).head(ExcelVO.class).sheet().registerReadListener(new AnalysisEventListener<ExcelVO>() {@Overridepublic void invoke(ExcelVO o, AnalysisContext analysisContext) {System.out.println(o);}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {System.out.println("文件解析完成");}}).doRead();}
}

4.寫數據

package com.southwind.handler;import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;import java.util.HashMap;
import java.util.List;
import java.util.Map;public class CustomCellWriteHandler extends AbstractColumnWidthStyleStrategy {private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);if (needSetWidth) {Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());if (maxColumnWidthMap == null) {maxColumnWidthMap = new HashMap<>();CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);}Integer columnWidth = this.dataLength(cellDataList, cell, isHead);if (columnWidth >= 0) {if (columnWidth > 255) {columnWidth = 255;}Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);}}}}private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {CellData cellData = cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch (type) {case STRING:return cellData.getStringValue().getBytes().length;case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}
}
package com.example;import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.southwind.handler.CustomCellWriteHandler;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;public class Test {public static void main(String[] args) throws Exception {List<ExcelVO> list = new ArrayList<>();for (int i = 0; i < 5; i++) {ExcelVO excelVO = new ExcelVO();excelVO.setId(i+1);excelVO.setType("臨時車");excelVO.setTime(new Date());excelVO.setPark("軟件園停車場");excelVO.setMoney(100);excelVO.setNumber("電A123456");excelVO.setName("Java科技有限公司");list.add(excelVO);}OutputStream outputStream = new FileOutputStream("D:\\java\\demo2.xls");EasyExcel.write(outputStream,ExcelVO.class).registerWriteHandler(new CustomCellWriteHandler()).sheet("停車繳費記錄").doWrite(list);}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/89662.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/89662.shtml
英文地址,請注明出處:http://en.pswp.cn/web/89662.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Openlayers 面試題及答案180道(141-160)

《前后端面試題》專欄集合了前后端各個知識模塊的面試題,包括html,javascript,css,vue,react,java,Openlayers,leaflet,cesium,mapboxGL,threejs,nodejs,mangoDB,MySQL,Linux… 。 前后端面試題-專欄總目錄 文章目錄 一、本文面試題目錄 141. 如何在生產環境中優…

LangChain面試內容整理-知識點24:實戰案例:智能助手 Agent 構建

本案例講述如何用LangChain構建一個結合多個工具的智能助手 Agent。智能助手需要理解用戶復雜請求,通過調用不同工具(如搜索、計算、查數據庫等)執行多步推理,再給出答案。LangChain的Agent框架非常適合這種場景。 構建步驟: 確定需求和選擇Agent類型:假設我們要一個能上…

【MATLAB例程】Taylor算法用于TOA(到達時間)的三維標簽位置解算,可自適應基站數量。附下載鏈接

本文給出自適應錨點&#xff08;基站&#xff09;的Taylor算法解算TOA&#xff08;到達時間&#xff09;的MATLAB代碼。參考論文&#xff1a;《基于Taylor-Chan算法的改進UWB室內三維定位方法》中的Taylor算法來解算TOA的復現程序&#xff08;MATLAB&#xff09;。 文章目錄運行…

Eclipse代碼折疊增強插件的安裝與使用

本文還有配套的精品資源&#xff0c;點擊獲取 簡介&#xff1a;Eclipse作為Java開發者的IDE&#xff0c;提供包括代碼折疊在內的多種功能&#xff0c;便于管理與閱讀代碼。本文介紹的“com.cb.eclipse.folding_1.0.6.jar”插件能夠進一步增強Eclipse的代碼折疊能力。安裝后&…

Python day18

浙大疏錦行 python day 18. 內容&#xff1a; 昨天學習了聚類算法的一些基本內容&#xff0c;今天繼續學習相關知識分析簇的特征和相關含義&#xff08;使用可視化來進行分析&#xff0c;也可以使用ai&#xff09; 代碼&#xff1a; shap.initjs() # 初始化 SHAP 解釋器 ex…

WPS文檔中心及文檔中臺遠程命令執行漏洞

【嚴重】WPS文檔中心及文檔中臺遠程命令執行漏洞 漏洞描述 WPS文檔中心是面向個人和企業的云端文檔存儲與管理平臺&#xff0c;WPS文檔中臺是為企業提供的集成化文檔協同與流程管理解決方案&#xff0c;強調API對接與業務系統整合。 在2024年5月之前通過docker私有化部署的版…

WPF 加載和顯示 GIF 圖片的完整指南

WPF 加載和顯示 GIF 圖片的完整指南 在 WPF 中加載和顯示 GIF 圖片需要一些特殊處理&#xff0c;因為 WPF 的 Image 控件默認不支持動畫 GIF。 解決方案一&#xff1a;使用 WpfAnimatedGif 庫&#xff08;推薦&#xff09; 這是最簡單且功能最完整的方法。 實現步驟&#xff1a…

Node.js GET/POST請求詳解

Node.js GET/POST請求詳解 引言 Node.js作為一種基于Chrome V8引擎的JavaScript運行環境&#xff0c;以其高性能、非阻塞I/O模型和輕量級等特點&#xff0c;在服務器端開發中得到了廣泛應用。本文將詳細介紹Node.js中GET和POST請求的處理方法&#xff0c;幫助開發者更好地理解和…

C++string類(2)

3.string類對象的訪問及遍歷操作函數名稱功能說明operator[] &#xff08;重 點&#xff09;返回pos位置的字符&#xff0c;const string類對象調用beginendbegin獲取第一個字符的迭代器 end獲取最后一個字符下一個位置的迭代器rbeginrendrbegin獲取最后一個字符的迭代器 ren…

SQLShift:一款異構數據庫存儲過程遷移工具

SQLShift 是一款專注于解決企業級數據庫遷移難題的智能 SQL 方言轉換平臺&#xff0c;尤其擅長異構數據庫存儲過程的自動化遷移。 SQLShift 工具深度融合了 AI 與 SQL 語法專家模型&#xff0c;可以大幅提升遷移效率并降低人工適配風險。 功能特性 多源多目標&#xff1a;目前…

學習設計模式《十八》——備忘錄模式

一、基礎概念 備忘錄模式的本質是【保存和恢復內部狀態】。 備忘錄模式的思考序號備忘錄模式的思考說明1保存是手段&#xff0c;恢復才是目的標準的備忘錄模式保存數據的手段是通過內存緩存&#xff1b;廣義的備忘錄模式實現的時候&#xff0c;可以采用離線存儲的方式&#xff…

HOT100——排序篇Leetcode215. 數組中的第K個最大元素

文章目錄題目&#xff1a;Leetcode215. 數組中的第K個最大元素原題鏈接思路1代碼1思路2代碼2題目&#xff1a;Leetcode215. 數組中的第K個最大元素 原題鏈接 數組中的第K個最大元素 思路1 排序 排序后返回倒數第k個數 代碼1 思路2 使用priority_queue&#xff0c;大根堆&#x…

三維重建一: 相機幾何

參考這位大佬&#xff1a;https://zhuanlan.zhihu.com/p/458000359 一. 基本的投影模型 正如上面所說&#xff0c;相機是一個將三維物體投影為二維圖像的設備。 對于小孔相機&#xff0c;或者薄透鏡相機來說&#xff0c;基礎投影的數學模型可以表達為 我們把這個過程表達在笛…

mysql 字符集不一致導致索引失效問題

mysql 字符集不一致導致索引失效問題 問題&#xff1a; 兩張表&#xff0c;同一個字段&#xff0c;由于字符集不一致&#xff0c;導致雖然都有索引&#xff0c;在關聯查詢時&#xff0c;索引失效身份表 identity_info &#xff0c;查詢索引信息 show index from identity_info …

Linux內核設計與實現 - 第6章 內核數據結構

目錄1. 鏈表 (Linked Lists)2. 隊列 (Queues)3. 映射 (Maps)4. 二叉樹 (Binary Trees)5. 位圖 (Bitmaps)6. 其他數據結構性能考量1. 鏈表 (Linked Lists) 單向鏈表 vs 雙向鏈表 struct list_head 標準實現內核鏈表API&#xff1a;LIST_HEAD(), list_add(), list_del() 環形鏈表…

十五、K8s可觀測能力:日志收集

十五、K8s可觀測能力&#xff1a;日志收集 文章目錄十五、K8s可觀測能力&#xff1a;日志收集1、云原生日志框架-ECK介紹1.1 什么是ECK&#xff1f;1.2 ECK核心資源&#xff1a;1.3 生產級日志收集架構2、日志收集-ECK2.1 集群規劃2.2 ECK 安裝2.3 一鍵部署高可用 ES 集群2.4 一…

微服務變更?自動化測試利器Parasoft SOAtest修復快、準、穩!

微服務架構憑借靈活和可擴展的優勢越來越普及&#xff0c;但隨之而來的變更也成了開發團隊的“心頭大患”。服務之間依賴復雜&#xff0c;接口改來改去&#xff0c;不僅讓開發更費勁&#xff0c;還容易導致測試用例失效、測試效率下降&#xff0c;甚至埋下系統不穩的隱患。 自…

將Android Studio創建的一個apk工程放到Android15源碼中構建

背景描述&#xff1a;起初Android Studio創建的apk工程&#xff0c;為了方便系統版本發布和后期維護需要同時支持兩種構建方式&#xff1a;Android Studio Gradle構建 IDE界面環境&#xff0c;對習慣java環境變成的友好、UI設計方便看效果Android15系統構建時自動構建 So…

yolo8目標檢測+訓練(識別和平精英人物)

?步驟一&#xff1a;安裝 PyTorch&#xff08;M1 專用&#xff09;# 推薦使用官方 MPS 后端&#xff08;Apple Metal 加速&#xff09; pip install torch torchvision torchaudio確認是否使用了 Apple MPS&#xff1a;import torch print(torch.backends.mps.is_available()…

【ArcGISPro】修改conda虛擬安裝包路徑

問題在ArcGISPro中經常使用克隆&#xff0c;導致C盤默認虛擬安裝包內存越來越大&#xff0c;導致電腦很卡解決方案打開ArcGISPro所在conda文件夾D:\Program Files\ArcGIS\Pro\bin\Python\Scripts打開命令行工具&#xff08;如 CMD 或終端&#xff09;。輸入以下命令&#xff0c…