用 Apache POI 读取 XLSX 数据
最近因为项目的原因,需要从一些 Microsoft Office Excel 文件读取数据并加载到数据库。
Google了一下方法,发现其实可以用的 Java 第三方库很多,最著名的是 Apache 的 POI 开源项目,其官网地址是 https://poi.apache.org
从首页的简介中我发现这个项目功能非常强大,不仅能处理 Excel,它还可以处理 Word、PowerPoint、Outlook、Visio,基本上囊括了 MS Office 的全部常用组件。目前 POI 更新到了 3.16 版本,可以从这个页面下载 https://poi.apache.org/download.html#POI-3.16
和所有的 Apache 开源项目一样,POI 下载页面同时提供源码和编译好的库文件下载,有时间的朋友建议下源码看看,写得非常好(编译用 ant 就行)。下载好库文件后(或者下载源文件自己编译好后),以 External Jars 的形式导入 Eclipse 项目中,就可以开始编程了。
读取 Excel 其实很简单,步骤如下:
1. 使用一个 java.io.FileInputStream 对象打开要访问的 Excel 文件获取一个输入流
2. 用这个文件流创建一个 org.apache.poi.xssf.usermodel.XSSFWorkbook 类的实例
3. 使用 XSSFWorkbook 类的 getSheetAt(int index) 方法读取指定的 sheet,其返回一个 org.apache.poi.xssf.usermodel.XSSFSheet 类的实例
4. 使用 XSSFSheet 类的 getRow(int index) 方法读取指定的 row(这里可以进行一个循环,详情请参阅下面的代码),其返回一个 org.apache.poi.xssf.usermodel.XSSFRow 类的实例
5. 使用 XSSFRow 类的 getCell(int index) 方法读取指定的 cell(同上,可以循环读取,参阅代码),其返回一个 org.apache.poi.xssf.usermodel.XSSFCell 类的实例
6. 根据返回的 Cell 的不同类型,分别处理:字符型数字型直接输出,日期型可以指定一个格式输出,表达式则需要使用 org.apache.poi.ss.usermodel.FormulaEvaluator 类的 evaluate(Cell arg0) 方法先得到表达式的值,然后再进行第二次类型判断后才能输出。
PS:因为目标数据的特性,我只需要把数据输出到标准输出即可。
完整程序如下:
package com.peisu.xlsx;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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;
public class XLSXLoader {
//Define the variables
private static InputStream inputStream;
private static XSSFWorkbook xssfWorkbook;
private static FormulaEvaluator formulaEvaluator;
private static int maxCellCount = 0;
//args[0]: the path to the xlsx file
//args[1]: the sheet number to process, start from 0
//args[2]: the date format output to standard output, for example, yyyy-MM-dd
//args[3]: start from which line to read, if there is a header, start from line 1
public static void main(String[] args) {
try {
//Open the input stream from the file, initialize the workbook
inputStream = new FileInputStream(args[0]);
xssfWorkbook = new XSSFWorkbook(inputStream);
formulaEvaluator = xssfWorkbook.getCreationHelper().createFormulaEvaluator();
//Open the sheet
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(Integer.valueOf(args[1]));
if (xssfSheet != null){
//Get the first row of the sheet
XSSFRow firstXSSFRow = xssfSheet.getRow(0);
if (firstXSSFRow != null){
//Set the max cell count to be the last cell number of the first line
maxCellCount = firstXSSFRow.getLastCellNum();
//Loop to read the rows
for (int rowNum = Integer.valueOf(args[3]);rowNum <= xssfSheet.getLastRowNum();rowNum++) {
//Get the row
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null){
//Loop to read the cells
for (int cellNum = 0;cellNum < maxCellCount;cellNum++){
//Get the cell
XSSFCell xssfCell = xssfRow.getCell(cellNum);
if (xssfCell != null){
//Process the cell based on the cell type
switch (xssfCell.getCellTypeEnum()){
case STRING:
System.out.print(xssfCell.getStringCellValue());
break;
case NUMERIC:
//If the cell matches the date format, output the cell as a date
if (DateUtil.isCellDateFormatted(xssfCell)) {
SimpleDateFormat dateFormat = new SimpleDateFormat(args[2]);
System.out.print(dateFormat.format(xssfCell.getDateCellValue()));
}
else
System.out.print(xssfCell.getNumericCellValue());
break;
case BOOLEAN:
System.out.print(xssfCell.getBooleanCellValue());
break;
case FORMULA:
//For formula cell, evaluate the formula to get the result
CellValue cellValue = formulaEvaluator.evaluate(xssfCell);
//Process the formula cell based on the type of the result
switch(cellValue.getCellTypeEnum()){
case STRING:
System.out.print(xssfCell.getStringCellValue());
break;
case NUMERIC:
//If the result matches the date format, output the result as a date
if (DateUtil.isCellDateFormatted(xssfCell)) {
SimpleDateFormat dateFormat = new SimpleDateFormat(args[2]);
System.out.print(dateFormat.format(xssfCell.getDateCellValue()));
}
else
System.out.print(xssfCell.getNumericCellValue());
break;
case BOOLEAN:
System.out.print(xssfCell.getBooleanCellValue());
break;
default:
System.out.print(xssfCell.getRawValue());
}
break;
case ERROR:
//System.out.print(xssfCell.getErrorCellString());
System.out.print("");
break;
default:
System.out.print(xssfCell.getRawValue());
}
}
//Add a column delimiter between the output cells
if(cellNum < maxCellCount - 1)
System.out.print("\t");
}
}
//Add a row delimiter between the output rows
System.out.println("");
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
xssfWorkbook.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
用 Apache POI 读取 XLSX 数据的更多相关文章
- apache poi 读取xlsx并导出为json(没考虑xls)
1.用到的jar包:fastjson-1.2.9.poi(poi-3.15.poi-ooxml-3.15.poi-ooxml-schemas-3.15.xmlbeans-2.6.0.commons-c ...
- 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据
1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...
- Java开发小技巧(六):使用Apache POI读取Excel
前言 在数据仓库中,ETL最基础的步骤就是从数据源抽取所需的数据,这里所说的数据源并非仅仅是指数据库,还包括excel.csv.xml等各种类型的数据接口文件,而这些文件中的数据不一定是结构化存储的, ...
- 使用poi读取excel数据示例
使用poi读取excel数据示例 分两种情况: 一种读取指定单元格的值 另一种是读取整行的值 依赖包: <dependency> <groupId>org.apache.poi ...
- 使用poi读取xlsx中的数据
excel中的内容见下图: 详细代码: package dataprovider; import java.io.FileInputStream; import java.io.InputStream ...
- 基于Apache POI 从xlsx读出数据
[0]写在前面 0.1) these codes are from 基于Apache POI 的从xlsx读出数据 0.2) this idea is from http://cwind.iteye. ...
- 基于Apache POI 向xlsx写入数据
[0]写在前面 0.1) these codes are from 基于Apache POI 的向xlsx写入数据 0.2) this idea is from http://cwind.iteye. ...
- Java POI读取Excel数据,将数据写入到Excel表格
1.准备 首先需要导入poi相应的jar包,包括: 下载地址:http://pan.baidu.com/s/1bpoxdz5 所需要的包的所在位置包括: 2.读取Excel数据代码 package S ...
- POI读取Excel数据保存到数据库,并反馈给用户处理信息(导入带模板的数据)
今天遇到这么一个需求,将课程信息以Excel的形式导入数据库,并且课程编号再数据库中不能重复,也就是我们需要先读取Excel提取信息之后保存到数据库,并将处理的信息反馈给用户.于是想到了POI读取文件 ...
随机推荐
- [LOJ6235]区间素数个数
题目大意: 给定$n(n\leq10^{11})$,求$\pi(n)$. 思路: 计算$\pi$函数有$O(n^{\frac23})$的Lehmer算法,这里考虑$O(\frac{n^{\frac34 ...
- Java 在Word创建表格
表格作为一种可视化交流模式及组织整理数据的手段,在各种场合及文档中应用广泛.常见的表格可包含文字.图片等元素,我们操作表格时可以插入图片.写入文字及格式化表格样式等.下面,将通过Java编程在Word ...
- codeigniter 使用
CodeIgniter系列 记录count和分页 对于某个表的不带条件的count,可以简单的用 $total = $this->db->count_all($table_name) 来获 ...
- 11G在用EXP导出时,空表不能导出
11G中有个新特性,当表无数据时,不分配segment,以节省空间 解决方法: 1.insert一行,再rollback就产生segment了. 该方法是在在空表中插入数据,再删除,则产生segmen ...
- Flutter开发记录part2
(1)文本超出折叠:child: Text('跑马灯dddd的范德萨范德萨放多少范德萨范德萨范德萨范德萨范德萨发',maxLines: 1,overflow: TextOverflow.ellipsi ...
- VirtualBox导入XXXX.vdi时报错
virtualbox导入vdi文件时出现以下的问题: 解决方法: windows+R,输入cmd,进入virtualbox的安装文件夹(或者在硬盘中直接进入virtualbox的安装文件夹.在任务栏里 ...
- oracle exchange partition 測试
Exchange partition提供了一种方式,让你在表与表或分区与分区之间迁移数据.注意不是将表转换成分区或非分区的形式,而仅仅仅是迁移表中数 据(互相迁移),因为其号称是採用了更改数据字典的 ...
- Linux学习之十九-Linux磁盘管理
Linux磁盘管理 1.相关知识 磁盘,是计算机硬件中不可或缺的部分磁盘,是计算机的外部存储器中类似磁带的装置,将圆形的磁性盘片装在一个方的密封盒子里,这样做的目的是为了防止磁盘表面划伤,导致数据丢失 ...
- IntelliJ IDEA 识别一个类所属的jar包package
IntelliJ IDEA 识别一个类所属的jar包package 按住ctrl,鼠标移动上去,不要点击: 有木有快捷键? ctrl+alt+B直接就过去了:需要再跳回来:
- Win2003 IIS 安装方法 图文教程
最近水一水 质量不高 见谅 一般大家先安装好win2003系统,图文教程 Win2003 服务器系统安装图文教程要通过控制面板来安装.具体做法为: 1. 进入“控制面板”. 2. 双击“添加或删除程序 ...