Apache-POI读取Excel2003和Excel2007中数据。

2023-10-19 17:40

本文主要是介绍Apache-POI读取Excel2003和Excel2007中数据。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

首先在F盘下的poiExcelTest文件夹下建立2个文件:student2003.xls和student2007.xlsx,如图
这里写图片描述
内容为:
这里写图片描述
2个文件中的内容一样

由于Excel2003和Excel2007数据读取方式不一样,
Excel2003需要用HSSF…开头的类,Excel2007需要XSSF…开头的类,所以,通过判断文件后缀名之后用不同的方法来读取,
这里写图片描述
本测试中用到的jar在这里下载就行了

点击这里下载jar:这里写图片描述

一下是测试代码:

package com.apache.poi.process.excel.poi.Excel.Test;import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.XLSBUnsupportedException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import com.apache.poi.process.excel.poi.Excel.model.Student;/*** POI读取Excel实例,分2003和2007* * @author zhangpei* */
public class ReadExcel {private static String xls2003 = "F:\\poiExcelTest\\student2003.xls";private static String xls2007 = "F:\\poiExcelTest\\student2007.xlsx";/*** 将Excel2003的数据读取做处理* * @param filePath* @return*/private static List<Student> readFromXLS2003(String filePath) {File excelFile = null;// Excel文件对象InputStream is = null;// 输入流对象String cellStr = null;// 单元格,最终按字符串处理List<Student> studentList = new ArrayList<Student>();// 返回封装数据的ListStudent student = null;// 每个学生信息对象try {excelFile = new File(filePath);is = new FileInputStream(excelFile);// 获取文件输入流HSSFWorkbook workbook2003 = new HSSFWorkbook(is);// 创建Excel2003文件对象HSSFSheet sheet = workbook2003.getSheetAt(0);// 取出第一个工作表,索引是0// 这里注意区分getLastRowNum()和getPhysicalNumberOfRows()的区别System.out.println("sheet.getLastRowNum():" + sheet.getLastRowNum());System.out.println("sheet.getPhysicalNumberOfRows():"+ sheet.getPhysicalNumberOfRows());// 开始循环遍历行,表头不处理,从1开始for (int i = 1; i <= sheet.getLastRowNum(); i++) {student = new Student();// 实例化Student对象HSSFRow row = sheet.getRow(i);// 获取行对象if (row == null) {// 如果为空,不处理continue;}// 如果row不为空,循环遍历单元格System.out.println("row.getLastCellNum:" + row.getLastCellNum());for (int j = 0; j < row.getLastCellNum(); j++) {HSSFCell cell = row.getCell(j);// 获取单元格对象if (cell == null) {// 如果为空,设置cellStr为空串cellStr = "";} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {// 对布尔值的处理cellStr = String.valueOf(cell.getBooleanCellValue());} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {// 对数字值的处理cellStr = cell.getNumericCellValue() + "";} else {// 其余按照字符串处理cellStr = cell.getStringCellValue();}// 下面按照数据出现的位置封装到bena中if (j == 0) {student.setName(cellStr);} else if (j == 1) {student.setGender(cellStr);} else if (j == 2) {student.setAge(new Double(cellStr).intValue());} else if (j == 3) {student.setSclass(cellStr);} else {student.setScore(new Double(cellStr).intValue());}}studentList.add(student);// 数据装入List}} catch (Exception e) {e.printStackTrace();} finally {// 关闭文件流if (is != null) {try {is.close();} catch (Exception e2) {e2.printStackTrace();}}}return studentList;}/*** 将Excel2007表格数据读取做处理*/public static List<Student> readFromXLSX2007(String filePath) {File excelFile = null;// Excel文件对象InputStream is = null;// 输入流对象String cellStr = null;// 单元格,最终按字符串处理List<Student> studentList = new ArrayList<Student>();// 返回封装数据的ListStudent student = null;// 每一个学生信息对象try {excelFile = new File(filePath);is = new FileInputStream(excelFile);// 获取文件输入流XSSFWorkbook workbook2007 = new XSSFWorkbook(is);// 创建Excel2007文件对象XSSFSheet sheet = workbook2007.getSheetAt(0);// 取出第一个工作表,索引为0// 这里注意区分getLastRowNum()和getPhysicalNumberOfRows()的区别System.out.println("sheet.getLastRowNum():" + sheet.getLastRowNum());System.out.println("sheet.getPhysicalNumberOfRows():"+ sheet.getPhysicalNumberOfRows());// 开始循环遍历行,表头不处理,从1开始for (int i = 1; i <= sheet.getLastRowNum(); i++) {student = new Student();// 实例化Student对象XSSFRow row = sheet.getRow(i);// 获取行对象if (row == null) {// 如果为空,不处理continue;}// row如果不为空,循环遍历单元格for (int j = 0; j < row.getLastCellNum(); j++) {XSSFCell cell = row.getCell(j);// 获取单元格对象if (cell == null) {// 单元格为空设置cellStr为空串cellStr = "";} else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {// 对布尔值的处理cellStr = String.valueOf(cell.getBooleanCellValue());} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {// 对数字值的处理cellStr = cell.getNumericCellValue() + "";} else {// 其余按照字符串处理cellStr = cell.getStringCellValue();}// 下面按照数据出现位置封装到bean中if (j == 0) {student.setName(cellStr);} else if (j == 1) {student.setGender(cellStr);} else if (j == 2) {student.setAge(new Double(cellStr).intValue());} else if (j == 3) {student.setSclass(cellStr);} else {student.setScore(new Double(cellStr).intValue());}}studentList.add(student);// 数据装入List}} catch (Exception e) {e.printStackTrace();} finally {// 关闭文件流try {if (is != null) {is.close();}} catch (Exception e2) {e2.printStackTrace();}}return studentList;}/*** 测试从Excel2003中读取数据话费了的时间*/public void testReadExcel2003CostTime(String xlsPath) {long start = System.currentTimeMillis();List<Student> list = readFromXLS2003(xlsPath);for (Student student : list) {System.out.println(student);}long end = System.currentTimeMillis();long totalTime = end - start;System.out.println("一共花费了" + totalTime + "ms");}/*** 测试从Excel2007中读取数据话费了的时间*/public void testReadExcel2007CostTime(String xlsPath) {long start = System.currentTimeMillis();List<Student> list = readFromXLSX2007(xlsPath);for (Student student : list) {System.out.println(student);}long end = System.currentTimeMillis();long totalTime = end - start;System.out.println("一共花费了" + totalTime + "ms");}/*** 主函数方法调用* * @param args*/public static void main(String[] args) {ReadExcel readExcel = new ReadExcel();readExcel.testReadExcel2003CostTime(xls2003);readExcel.testReadExcel2007CostTime(xls2007);}
}

测试数据结果如下

sheet.getLastRowNum():4
sheet.getPhysicalNumberOfRows():5
row.getLastCellNum:5
row.getLastCellNum:5
row.getLastCellNum:5
row.getLastCellNum:5
Strudnet [age=23,gender=男,name=张三,sclass一班,score94]
Strudnet [age=20,gender=女,name=李四,sclass二班,score92]
Strudnet [age=21,gender=男,name=王五,sclass五班,score87]
Strudnet [age=22,gender=女,name=赵六,sclass三班,score83]
一共花费了143ms
sheet.getLastRowNum():4
sheet.getPhysicalNumberOfRows():5
Strudnet [age=23,gender=男,name=张三,sclass一班,score94]
Strudnet [age=20,gender=女,name=李四,sclass二班,score92]
Strudnet [age=21,gender=男,name=王五,sclass五班,score87]
Strudnet [age=22,gender=女,name=赵六,sclass三班,score83]
一共花费了413ms

这篇关于Apache-POI读取Excel2003和Excel2007中数据。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/241338

相关文章

SpringBoot实现接口数据加解密的三种实战方案

《SpringBoot实现接口数据加解密的三种实战方案》在金融支付、用户隐私信息传输等场景中,接口数据若以明文传输,极易被中间人攻击窃取,SpringBoot提供了多种优雅的加解密实现方案,本文将从原... 目录一、为什么需要接口数据加解密?二、核心加解密算法选择1. 对称加密(AES)2. 非对称加密(R

详解如何在SpringBoot控制器中处理用户数据

《详解如何在SpringBoot控制器中处理用户数据》在SpringBoot应用开发中,控制器(Controller)扮演着至关重要的角色,它负责接收用户请求、处理数据并返回响应,本文将深入浅出地讲解... 目录一、获取请求参数1.1 获取查询参数1.2 获取路径参数二、处理表单提交2.1 处理表单数据三、

Spring Validation中9个数据校验工具使用指南

《SpringValidation中9个数据校验工具使用指南》SpringValidation作为Spring生态系统的重要组成部分,提供了一套强大而灵活的数据校验机制,本文给大家介绍了Spring... 目录1. Bean Validation基础注解常用注解示例在控制器中应用2. 自定义约束验证器定义自

C#实现高性能Excel百万数据导出优化实战指南

《C#实现高性能Excel百万数据导出优化实战指南》在日常工作中,Excel数据导出是一个常见的需求,然而,当数据量较大时,性能和内存问题往往会成为限制导出效率的瓶颈,下面我们看看C#如何结合EPPl... 目录一、技术方案核心对比二、各方案选型建议三、性能对比数据四、核心代码实现1. MiniExcel

SQL常用操作精华之复制表、跨库查询、删除重复数据

《SQL常用操作精华之复制表、跨库查询、删除重复数据》:本文主要介绍SQL常用操作精华之复制表、跨库查询、删除重复数据,这些SQL操作涵盖了数据库开发中最常用的技术点,包括表操作、数据查询、数据管... 目录SQL常用操作精华总结表结构与数据操作高级查询技巧SQL常用操作精华总结表结构与数据操作复制表结

Redis中的数据一致性问题以及解决方案

《Redis中的数据一致性问题以及解决方案》:本文主要介绍Redis中的数据一致性问题以及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Redis 数据一致性问题的产生1. 单节点环境的一致性问题2. 网络分区和宕机3. 并发写入导致的脏数据4. 持

POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能

《POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能》ApachePOI是一个流行的Java库,用于处理MicrosoftOffice格式文件,提供丰富API来创建、读取和修改O... 目录前言:Apache POIEasyPoiEasyExcel一、EasyExcel1.1、核心特性

解决Maven项目报错:failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0的问题

《解决Maven项目报错:failedtoexecutegoalorg.apache.maven.plugins:maven-compiler-plugin:3.13.0的问题》这篇文章主要介... 目录Maven项目报错:failed to execute goal org.apache.maven.pl

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例