阿帕奇POI工具类

package com.llf.util;import com.llf.excel.User;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;/*** @Author llf* @Date 2022/1/12 15:09* @Version 1.0*/
public class ReadExcelUtil {/*** 根据path后缀  返回不同版本的excel** @param filePath 文件路径* @return* @throws IOException*/public static Workbook suffixChoose(String filePath) throws IOException {Workbook workbook = null;if (filePath == null) {return null;}String extString = filePath.substring(filePath.lastIndexOf("."));FileInputStream stream = null;//后缀类型判断try {stream = new FileInputStream(filePath);if (".xls".equals(extString)) {return  new HSSFWorkbook(stream);} else if (".xlsx".equals(extString)) {return new XSSFWorkbook(stream);} else {return  null;}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return workbook;}/*** 通过判断格式 为cell设定java可以表示的格式** @param cell* @return*/public static Object getCellFormatValue(Cell cell,Workbook sheets) {Object cellValue = null;XSSFFormulaEvaluator FormulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) sheets);if (cell != null) {int cellType = cell.getCellType();//判断cell类型switch (cellType) {case HSSFCell.CELL_TYPE_STRING://字符串类型cellValue = cell.getStringCellValue();break;case HSSFCell.CELL_TYPE_BOOLEAN://布尔类型cellValue = String.valueOf(cell.getBooleanCellValue());break;case HSSFCell.CELL_TYPE_BLANK://null 类型break;case HSSFCell.CELL_TYPE_NUMERIC://数字(普通数字、日期)类型if (HSSFDateUtil.isCellDateFormatted(cell)) {Date date = cell.getDateCellValue();cellValue = new DateTime(date).toString("yyyy-MM-dd");} else {//如果不是日期格式 就转换为string类型cell.setCellType(HSSFCell.CELL_TYPE_STRING);cellValue = cell.toString();}break;case HSSFCell.CELL_TYPE_ERROR://数据类型错误break;case HSSFCell.CELL_TYPE_FORMULA://如果是公式String formula = cell.getCellFormula();System.out.println("公式是:"+formula);try {cellValue = String.valueOf(cell.getNumericCellValue());} catch (IllegalStateException e) {cellValue = String.valueOf(cell.getRichStringCellValue());}break;default:cellValue = "";}} else {cellValue = "";}return cellValue;}/*** 通过path解析excel** @param path* @return* @throws IOException*/public static ArrayList<User> ResolveExcelByPath(String path) throws IOException {ArrayList<User> list = new ArrayList<>();//1.得到需要解析的文件Workbook sheets = suffixChoose(path);//2、通过表名称获取工作表对象Sheet sheet = sheets.getSheetAt(0);//获取表的总行数int rowNum = sheet.getPhysicalNumberOfRows();
//总列数int colNum = sheet.getRow(0).getLastCellNum();//获取表头Row row = sheet.getRow(0);if (row != null) {for (int i = 0; i < colNum; i++) {System.out.print(row.getCell(i) + "|");}}System.out.println();
//遍历excel每一行  从1开始 忽略表头for (int j = 1; j <= rowNum; j++) {//拿到每一列的值Row rowData = sheet.getRow(j);if (rowData != null) {Cell cell1 = rowData.getCell(0);
//获取表中第i行,第2列的单元格Cell cell2 = rowData.getCell(1);
//excel表的第i行,第3列的单元格Cell cell3 = rowData.getCell(2);
//excel表的第i行,第4列的单元格  依次类推Cell cell4 = rowData.getCell(3);
//这里new 一个对象,用来装填Excel数据,字段根据excel决定User user = new User();user.setSno((String) ReadExcelUtil.getCellFormatValue(cell1,sheets));user.setName((String) ReadExcelUtil.getCellFormatValue(cell2,sheets));user.setAge((String) ReadExcelUtil.getCellFormatValue(cell3,sheets));user.setBirth((String) ReadExcelUtil.getCellFormatValue(cell4,sheets));list.add(user);}}return list;}
}

这个工具类一共有三个方法suffixChoosegetCellFormatValueResolveExcelByPath

第一个方法用来判断文件类型是xls还是xlsx 并根据类型创建不同的Workbook对象

第二个方法用来将单元格的值进行识别 并格式化

第三个方法是主启动方法 将文件路径作为参数传入 然后解析

如果使用web页面怎么办

ResolveExcelByPath方法的参数 更改成MultipartFile file

使用WorkbookFactory.create方法 直接将file作为参数转换成流 得到sheets对象

    public static ArrayList<User> ResolveExcelByPath(MultipartFile file) throws IOException {//  Workbook sheets = suffixChoose(path); 注释掉这个方法即可Workbook sheets = WorkbookFactory.create(file.getInputStream());......}  

如果使用Swing界面怎么办?

package com.llf.excel;import com.llf.util.ReadExcelUtil;import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;/*** @Author llf* @Date 2022/1/12 18:08* @Version 1.0*/
public class test {public static void main(String[] args) throws IOException {String path = null;JFileChooser fc = new JFileChooser();fc.setDialogTitle("文件上传");fc.setApproveButtonText("确定");fc.setFileSelectionMode(JFileChooser.FILES_ONLY);if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(fc)) {path=fc.getSelectedFile().getPath();System.out.println(path);//这个path 就是excel文件的地址 然后调用 ResolveExcelByPath 方法即可ArrayList<User> list = ReadExcelUtil.ResolveExcelByPath(path);list.forEach(x->{System.out.println(x);});}}}

注意点

采用面向对象的思想 每一张不同表头的表都是一个新的对象,因此在进行解析的时候 就需要使用不用的实体对象来进行存储,因此只需要改动主方法中赋值的代码即可

            if (rowData != null) {Cell cell1 = rowData.getCell(0);
//获取表中第i行,第2列的单元格Cell cell2 = rowData.getCell(1);
//excel表的第i行,第3列的单元格Cell cell3 = rowData.getCell(2);
//excel表的第i行,第4列的单元格  依次类推Cell cell4 = rowData.getCell(3);// 有几列 就得到几个cell对象//这里new 一个对象,用来装填Excel数据,字段根据excel决定User user = new User();user.setSno((String) ReadExcelUtil.getCellFormatValue(cell1,sheets));user.setName((String) ReadExcelUtil.getCellFormatValue(cell2,sheets));user.setAge((String) ReadExcelUtil.getCellFormatValue(cell3,sheets));user.setBirth((String) ReadExcelUtil.getCellFormatValue(cell4,sheets));list.add(user);
package com.llf.excel;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** @Author llf* @Date 2022/1/12 14:04* @Version 1.0*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {private  String sno;private  String  name;private  String age;private  String birth;
}

如果还有不懂的 可以去B站 搜所狂神的poi教程 比较详细

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--文件上传解析--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.9</version></dependency><!--文件上传解析--><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.10</version></dependency></dependencies>

阿帕奇POI EXCEL解析相关推荐

  1. POI Excel解析

    Maven 引入POI <dependency><groupId>org.apache.poi</groupId><artifactId>poi< ...

  2. poi excel文档生成与读取

    阿帕奇poi excel文档操作 1. introduce 2. 轮子 3. demo 以九九乘法表为例 3.1 xls的生成 3.2 xlsx的生成 3.3 读取xlsx 1. introduce ...

  3. poi的excel解析工具类

    2019独角兽企业重金招聘Python工程师标准>>> import org.apache.commons.lang.StringUtils; import org.apache.c ...

  4. android excel 筛选功能,Android 实现 Excel 解析 xls 和 xlsx,方法也可以很简单

    Excel 解析,一般来说是在服务端进行的,但是如果移动端要实现解析Excel的功能,那也是有实现的方法的. 不过由于Android 原生用Java/Kotlin实现,所以也可以参考服务端解析Exce ...

  5. easyexcel一个很棒的Excel解析工具

    easyexcel一个很棒的Excel解析工具 前言 Excel格式 核心原理对比 理解与使用 总结 前言 最近手头上有一个项目,其中有一个需求就是要Excel表格导入导出,之前有过类似的经验,不过当 ...

  6. Excel解析工具easyexcel全面探索

    1. Excel解析工具easyexcel全面探索 1.1. 简介 之前我们想到Excel解析一般是使用POI,但POI存在一个严重的问题,就是非常消耗内存.所以阿里人员对它进行了重写从而诞生了eas ...

  7. Java POI Excel导入导出

    Java POI Excel导入导出 1.maven引入依赖 2.导入Excel 3.导出Excel 1.maven引入依赖 <!-- POI Excel 操作 --> <depen ...

  8. poi 图片解析-定位与读取

    java学习记录(6)- poi 图片解析-定位与读取 提要: 引言 代码 总结 1 引言:把excel中的内容转换到数据库中,是一个常见的工作. 而如果excel中有图片应该如何进行图片的操作,以及 ...

  9. SpringBoot excel解析自定义列、行数据

    1.excel解析任意数据 public class ParseExcelUtil {private static final Logger logger = LoggerFactory.getLog ...

最新文章

  1. 数据分析 同比是消除季节影响与去年同段时间比,环比是连续两个时间段比
  2. 计算机网络 浏览器发送http请求的过程分析
  3. Linux学习笔记——例说makefile 综合案例
  4. [Python]ConfigParser解析配置文件
  5. IDEA设置自定义代码模板
  6. 前端基础HTML5CSS3动画
  7. c语言 字母赋值给变量,C++变量(变量定义和赋值)详解
  8. CASE WHEN语句中加IN应该如何使用
  9. JDialog简单使用
  10. Java面试相关问题以及解析
  11. 【网络实验箱02】-odl-neutron北向抓包分析
  12. 罗格斯大学电子与计算机工程,罗格斯大学电子和计算机工程理学硕士研究生申请要求及申请材料要求清单...
  13. RGB24 To Yuv420 C语言 +汇编实现(windows平台)
  14. windows 11 访问带SMB的文件服务器(小米路由器)
  15. 谈谈我对于项目管理的认识!
  16. 微信小程序-模板与配置
  17. uefiboot 文件_UEFI BIOS模式下Windows系统启动过程以及引导文件修复方法
  18. 手机APP自动化 Appium教程
  19. 你真的足够了解Wi-Fi吗?
  20. if-else语句判断一个数字是大于等于或小于0【C++】

热门文章

  1. OpenCVSharp 笑脸检测
  2. (初学者)用python实现九九乘法表
  3. WPF:Margin属性和Padding属性
  4. 彻底理解setTimeout()
  5. 商号权的取得方式是什么
  6. 西安奔驰女车主已经达成和解,那其他问题车主怎么办?
  7. Aras入门教程0_Aras 2023 安装
  8. windows11如何更改鼠标样式(大小和颜色)
  9. 什么是区块链共识算法?
  10. zhi hu7w阅读,如何人在家中坐,offer天上来!年薪百万,财务自由只是刚刚开始?(内容太过真实,Android高级工程师必经之路!)