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

相关文章

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

异构存储(冷热数据分离)

异构存储主要解决不同的数据,存储在不同类型的硬盘中,达到最佳性能的问题。 异构存储Shell操作 (1)查看当前有哪些存储策略可以用 [lytfly@hadoop102 hadoop-3.1.4]$ hdfs storagepolicies -listPolicies (2)为指定路径(数据存储目录)设置指定的存储策略 hdfs storagepolicies -setStoragePo

Hadoop集群数据均衡之磁盘间数据均衡

生产环境,由于硬盘空间不足,往往需要增加一块硬盘。刚加载的硬盘没有数据时,可以执行磁盘数据均衡命令。(Hadoop3.x新特性) plan后面带的节点的名字必须是已经存在的,并且是需要均衡的节点。 如果节点不存在,会报如下错误: 如果节点只有一个硬盘的话,不会创建均衡计划: (1)生成均衡计划 hdfs diskbalancer -plan hadoop102 (2)执行均衡计划 hd

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

烟火目标检测数据集 7800张 烟火检测 带标注 voc yolo

一个包含7800张带标注图像的数据集,专门用于烟火目标检测,是一个非常有价值的资源,尤其对于那些致力于公共安全、事件管理和烟花表演监控等领域的人士而言。下面是对此数据集的一个详细介绍: 数据集名称:烟火目标检测数据集 数据集规模: 图片数量:7800张类别:主要包含烟火类目标,可能还包括其他相关类别,如烟火发射装置、背景等。格式:图像文件通常为JPEG或PNG格式;标注文件可能为X

pandas数据过滤

Pandas 数据过滤方法 Pandas 提供了多种方法来过滤数据,可以根据不同的条件进行筛选。以下是一些常见的 Pandas 数据过滤方法,结合实例进行讲解,希望能帮你快速理解。 1. 基于条件筛选行 可以使用布尔索引来根据条件过滤行。 import pandas as pd# 创建示例数据data = {'Name': ['Alice', 'Bob', 'Charlie', 'Dav

SWAP作物生长模型安装教程、数据制备、敏感性分析、气候变化影响、R模型敏感性分析与贝叶斯优化、Fortran源代码分析、气候数据降尺度与变化影响分析

查看原文>>>全流程SWAP农业模型数据制备、敏感性分析及气候变化影响实践技术应用 SWAP模型是由荷兰瓦赫宁根大学开发的先进农作物模型,它综合考虑了土壤-水分-大气以及植被间的相互作用;是一种描述作物生长过程的一种机理性作物生长模型。它不但运用Richard方程,使其能够精确的模拟土壤中水分的运动,而且耦合了WOFOST作物模型使作物的生长描述更为科学。 本文让更多的科研人员和农业工作者