读取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. Grid++Report报表工具C/S实战篇(五)

    一.课程介绍 本次分享课程属于<C#高级编程实战技能开发宝典课程系列>中的第五部分,阿笨后续会计划将实际项目中的一些比较实用的关于C#高级编程的技巧分享出来给大家进行学习,不断的收集.整理 ...

  2. wpf 的依赖属性只能在loaded 事件之后才能取到

    wpf 的依赖属性只能在loaded 事件之后才能取到,在构造函数的  InitializeComponent(); 之后取不到 wpf 的依赖属性只能在loaded 事件之后才能取到,在构造函数的  ...

  3. WPF Command CanExecute 触发一次的问题

    昨天在项目中遇到一个问题,按钮bind了Command后,利用CanExecute控制它的是否可点击.结果却在初始化viewmodel的时候执行了一次CanExecute,之后一直不触发,按钮的可用性 ...

  4. Python运维脚本整理

    Python 实现的自动化服务器管理 import sys import os import paramiko ssh = paramiko.SSHClient() ssh.set_missing_h ...

  5. Django(ORM查询1)

    day69 参考:http://www.cnblogs.com/liwenzhou/p/8660826.html 在Python脚本中调用Django环境 orm1.py import os if _ ...

  6. Android在onCreate中获取控件的宽高

    在某些需求下,我们需要在onCreate的时候就获取到控件的宽高,但是如果直接用view.getWidth()或view.getHeight()会得到0.这是因为在onCreate执行的时候,控件还没 ...

  7. Swift5 语言参考(九) 泛型和参数

    本章介绍泛型类型,函数和初始值设定项的参数和参数.声明泛型类型,函数,下标或初始化程序时,可以指定泛型类型,函数或初始化程序可以使用的类型参数.当创建泛型类型的实例或调用泛型函数或初始化程序时,这些类 ...

  8. 10-02 Java 形式参数和返回值的问题深入研究,链式编程

    形式参数和返回值的问题: 1:形式参数和返回值的问题(理解) (1)形式参数: 类名:需要该类的对象 抽象类名:需要该类的子类对象 接口名:需要该接口的实现类对象 (2)返回值类型: 类名:返回的是该 ...

  9. Matlab中常见的神经网络训练函数和学习函数

    一.训练函数 1.traingd Name:Gradient descent backpropagation (梯度下降反向传播算法 ) Description:triangd is a networ ...

  10. 一个对眼睛很好的vim 颜色主题

    地址:https://github.com/altercation/vim-colors-solarized 安装: $ cd vim-colors-solarized/colors $ mv sol ...