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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈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…