读取excel,首先需要下载POI的jar,可以去官网下,也可以在这里下载

一、简单说明

excel2003和excel2007区别比较大,最直观的感受就是扩展名不一样,哈哈

不过,使用POI的API都是面向接口编程的,实际使用起来区别其实不大(知道为什么要面向接口编程了吗?好处就在这里,O(∩_∩)O哈哈~)

代码最直观,直接看代码

二、范例

package com.hundsun.excel.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream; 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.apache.xmlbeans.impl.piccolo.io.FileFormatException; public class ReadExcelTest { private static final String EXTENSION_XLS = "xls";
private static final String EXTENSION_XLSX = "xlsx"; /***
* <pre>
* 取得Workbook对象(xls和xlsx对象不同,不过都是Workbook的实现类)
* xls:HSSFWorkbook
* xlsx:XSSFWorkbook
* @param filePath
* @return
* @throws IOException
* </pre>
*/
private Workbook getWorkbook(String filePath) throws IOException {
Workbook workbook = null;
InputStream is = new FileInputStream(filePath);
if (filePath.endsWith(EXTENSION_XLS)) {
workbook = new HSSFWorkbook(is);
} else if (filePath.endsWith(EXTENSION_XLSX)) {
workbook = new XSSFWorkbook(is);
}
return workbook;
} /**
* 文件检查
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
private void preReadCheck(String filePath) throws FileNotFoundException, FileFormatException {
// 常规检查
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException("传入的文件不存在:" + filePath);
} if (!(filePath.endsWith(EXTENSION_XLS) || filePath.endsWith(EXTENSION_XLSX))) {
throw new FileFormatException("传入的文件不是excel");
}
} /**
* 读取excel文件内容
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
public void readExcel(String filePath) throws FileNotFoundException, FileFormatException {
// 检查
this.preReadCheck(filePath);
// 获取workbook对象
Workbook workbook = null; try {
workbook = this.getWorkbook(filePath);
// 读文件 一个sheet一个sheet地读取
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
System.out.println("=======================" + sheet.getSheetName() + "========================="); int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum(); // 读取首行 即,表头
Row firstRow = sheet.getRow(firstRowIndex);
for (int i = firstRow.getFirstCellNum(); i <= firstRow.getLastCellNum(); i++) {
Cell cell = firstRow.getCell(i);
String cellValue = this.getCellValue(cell, true);
System.out.print(" " + cellValue + "\t");
}
System.out.println(""); // 读取数据行
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);// 当前行
int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {
Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
String currentCellValue = this.getCellValue(currentCell, true);// 当前单元格的值
System.out.print(currentCellValue + "\t");
}
System.out.println("");
}
System.out.println("======================================================");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} /**
* 取单元格的值
* @param cell 单元格对象
* @param treatAsStr 为true时,当做文本来取值 (取到的是文本,不会把“1”取成“1.0”)
* @return
*/
private String getCellValue(Cell cell, boolean treatAsStr) {
if (cell == null) {
return "";
} if (treatAsStr) {
// 虽然excel中设置的都是文本,但是数字文本还被读错,如“1”取成“1.0”
// 加上下面这句,临时把它当做文本来读取
cell.setCellType(Cell.CELL_TYPE_STRING);
} if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
} }

三、其他

本人在Excel2010上试的时候,excel中明明设置的都是文本类型,但是读取的时候,把数字“1”读成“1.0”

所以在getCellValue()方法中,把cell单元格的式样改了一下,确保数字“1”文本读出来还是“1”

Java读取excel(兼容03和07格式)的更多相关文章

  1. php读取excel(支持03,07)

    需要用到PHPExcel这个类 附上代码 //phpExcel读取excel内容 header("Content-Type:textml;charset=utf-8"); //引用 ...

  2. java读取excel或者csv时日期格式数据处理

    背景:最近写一个通过excel批量导入数据的功能,里面含有时间,但是java读取之后把时间转为了距离1990年1月1号的天数,比如excel中时间为2018/9/16 18:30,java读取之后变成 ...

  3. Java读取excel 支持xls 和 xlsx格式

    1.工具类public class InExcelTool { //根据指定位置单独读取一个 public static String getContent(String file, int page ...

  4. Java读取excel表格

    Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...

  5. Java读取Excel数据

    Java读取Excel数据,解析文本并格式化输出 Java读取Excel数据,解析文本并格式化输出 Java读取Excel数据,解析文本并格式化输出 下图是excel文件的路径和文件名 下图是exce ...

  6. Java读取Excel文件的几种方法

    Java读取 Excel 文件的常用开源免费方法有以下几种: 1. JDBC-ODBC Excel Driver 2. jxl.jar 3. jcom.jar 4. poi.jar 简单介绍: 百度文 ...

  7. java读取excel文件的代码

    如下内容段是关于java读取excel文件的内容,应该能对各朋友有所用途. package com.zsmj.utilit; import java.io.FileInputStream;import ...

  8. 关于解决java读取excel文件遇空行抛空指针的问题 !

    关于解决java读取excel文件遇空行抛空指针的问题 ! package exceRead; import java.io.File; import java.io.FileInputStream; ...

  9. java读取excel文件数据导入mysql数据库

    这是我来公司的第二周的一个小学习任务,下面是实现过程: 1.建立maven工程(方便管理jar包) 在pom.xml导入 jxl,mysql-connector 依赖 可以在maven仓库搜索 2.建 ...

随机推荐

  1. Seaching TreeVIew WPF

    项目中有一个树形结构的资源,需要支持搜索功能,搜索出来的结果还是需要按照树形结构展示,下面是简单实现的demo. 1.首先创建TreeViewItem的ViewModel,一般情况下,树形结构都包含D ...

  2. AJPFX外汇的常见形态

    AJPFX:外汇价常见形态 外汇的价格,本质上是由供求关系决定的,但是在技术分析的世界里,是什么原因导致供求关系的改变并不重要,也没有人能准确的找出所有的因素并加以判断,但是供求关系被改变后的外汇走势 ...

  3. GITLAB安装笔记

    CentOS 7 最小安装后操作 设置时区timedatectl set-timezone Asia/Shanghai 添加 Gitlab 清华源 vi /etc/yum.repos.d/gitlab ...

  4. Flask-SQLAlchemy插件

    一,初始化 两种方式: db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) return app ap ...

  5. 13-01 java StringBuffer类,StringBuilder类

    StringBuffer类的构造方法 package cn.itcast_01; /* * 线程安全(多线程讲解) * 安全 -- 同步 -- 数据是安全的 * 不安全 -- 不同步 -- 效率高一些 ...

  6. C#简单操作MongoDB

    一 安装MongoDB 官网按需下载, 安装, 一步到位. 二 VS创建新项目 创建一个.netcore console项目, 然后nuget安装驱动MongoDB.Driver 三 建立连接 在Pr ...

  7. 使用代码查看Nutch爬取的网站后生成的SequenceFile信息

    必须针对data文件中的value类型来使用对应的类来查看(把这个data文件,放到了本地Windows的D盘根目录下). 代码: package cn.summerchill.nutch; impo ...

  8. 高可用Hadoop平台-答疑篇

    1.概述 这篇博客不涉及到具体的编码,只是解答最近一些朋友心中的疑惑.最近,一些朋友和网友纷纷私密我,我总结了一下,疑问大致包含以下几点: 我学 Hadoop 后能从事什么岗位? 在遇到问题,我该如何 ...

  9. Vue笔记:使用node开发vue入门实例

    安装NPM 首先在命令终端输入 npm -v 检测是否安装 npm.如果没有,按照下面教程进行安装. 下载地址: nodejs中文网 到官网下载自己系统对应的版本,这里我们下载Windows系统的64 ...

  10. rpmbuild 源码打包clickhouse,附带打好的rpm包下载地址

    一.下载 clickhouse 源码包 git clone --recurse-submodules -b v1.1.54385-stable https://github.com/yandex/Cl ...