JAVA导入(读取)Excel中的数据(支持xls与xlsx文件)
一、导入jar包
poi-3.7.jar
poi-scratchpad-3.7.jar
poi-examples-3.7.jar
poi-ooxml-3.7.jar
poi-ooxml-schemas-3.7.jar
xmlbeans-2.3.0.jar
maven
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.7</version>
</dependency>
jar包下载地址:https://yvioo.lanzous.com/b00no8wbe
密码:eln5
二、编写工具类ExcelTool.java
package com.test; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell; import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; public class ExcelTool {
public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
public static final String EMPTY = "";
public static final String POINT = ".";
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
/**
* 获得path的后缀名
* @param path
* @return
*/
public static String getPostfix(String path){
if(path==null || EMPTY.equals(path.trim())){
return EMPTY;
}
if(path.contains(POINT)){
return path.substring(path.lastIndexOf(POINT)+1,path.length());
}
return EMPTY;
}
/**
* 单元格格式
* @param hssfCell
* @return
*/
@SuppressWarnings({ "static-access", "deprecation" })
public static String getHValue(HSSFCell hssfCell){
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
String cellValue = "";
if(HSSFDateUtil.isCellDateFormatted(hssfCell)){
Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());
cellValue = sdf.format(date);
}else{
DecimalFormat df = new DecimalFormat("#.##");
cellValue = df.format(hssfCell.getNumericCellValue());
String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
if(strArr.equals("00")){
cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
}
}
return cellValue;
} else {
return String.valueOf(hssfCell.getStringCellValue());
}
}
/**
* 单元格格式
* @param xssfCell
* @return
*/
public static String getXValue(XSSFCell xssfCell){
if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfCell.getBooleanCellValue());
} else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
String cellValue = "";
if(XSSFDateUtil.isCellDateFormatted(xssfCell)){
Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());
cellValue = sdf.format(date);
}else{
DecimalFormat df = new DecimalFormat("#.##");
cellValue = df.format(xssfCell.getNumericCellValue());
String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
if(strArr.equals("00")){
cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
}
}
return cellValue;
} else {
return String.valueOf(xssfCell.getStringCellValue());
}
}
/**
* 自定义xssf日期工具类
* @author lp
*
*/
static class XSSFDateUtil extends DateUtil {
protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
return DateUtil.absoluteDay(cal, use1904windowing);
}
}
}
三、编写调用类ExcelUtils.java(File类型使用)
import com.test.ExcelTool;
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.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*; import java.util.ArrayList;
import java.util.List; public class ExcelUtils { public static int totalRows; //sheet中总行数
public static int totalCells; //每一行总单元格数 /**
* read the Excel .xlsx,.xls
* @param file jsp中的上传文件
* @return
* @throws IOException
*/
public static List<ArrayList<String>> readExcel(File file) throws IOException {
if(file==null){
return null;
}else{
String postfix = ExcelTool.getPostfix(file.getName());
if(!ExcelTool.EMPTY.equals(postfix)){
if(ExcelTool.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
return readXls(file);
}else if(ExcelTool.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
return readXlsx(file);
}else{
return null;
}
}
}
return null;
} /**
* read the Excel 2010 .xlsx
* @param file
* @return
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static List<ArrayList<String>> readXlsx(File file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
XSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = new FileInputStream(file);
// 创建文档
wb = new XSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
if(xssfSheet == null){
continue;
}
totalRows = xssfSheet.getLastRowNum();
//读取Row,从第二行开始
for(int rowNum = 0;rowNum <= totalRows;rowNum++){
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if(xssfRow!=null){
rowList = new ArrayList<String>();
totalCells = xssfRow.getLastCellNum();
//读取列,从第一列开始
for(int c=0;c<=totalCells+1;c++){
XSSFCell cell = xssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelTool.EMPTY);
continue;
}
rowList.add(ExcelTool.getXValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null; }
/**
* read the Excel 2003-2007 .xls
* @param file
* @return
* @throws IOException
*/
public static List<ArrayList<String>> readXls(File file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
HSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = new FileInputStream(file);
// 创建文档
wb = new HSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
if(hssfSheet == null){
continue;
}
totalRows = hssfSheet.getLastRowNum();
//读取Row,从第二行开始
for(int rowNum = 0;rowNum <= totalRows;rowNum++){
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if(hssfRow!=null){
rowList = new ArrayList<String>();
totalCells = hssfRow.getLastCellNum();
//读取列,从第一列开始
for(short c=0;c<=totalCells+1;c++){
HSSFCell cell = hssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelTool.EMPTY);
continue;
}
rowList.add(ExcelTool.getHValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} }
四、调用方法
1、本地调用方式
public static void main(String[] args) throws Exception {
File file = new File("E:\\导入模板表.xlsx");
List<ArrayList<String>> list = ExcelUtils.readExcel(file);
for (int i = 0; i < list.size(); i++) {
//第一行全部数据
List list1=list.get(i);
for (int j = 0; j < list1.size(); j++) {
//第一行每个单元格数据
System.out.println(list1.get(j));
}
}
}
2、JavaWeb调用方式(只需把上面的方法中File类型改成MultipartFile类型,使用以下的ExcelUtils类)
@RequestMapping(value = "o_import.do",method = RequestMethod.POST)
public String importXls(
@RequestParam(value = "Filedata", required = false) MultipartFile file) {
try {
//list为excel数据集合
List<ArrayList<String>> list = ExcelUtils.readExcel(file);
for (int i = 0; i < list.size(); i++) {
//第一行数据集合
List list1=list.get(i);
for (int j = 0; j < list1.size(); j++) {
//第一行每个单元格数据
System.out.println(list1.get(j));
} } } catch (Exception e) {
e.printStackTrace();
}
return null;
}
ExcelUtils类(MultipartFile类型使用)
import org.apache.poi.hssf.usermodel.*;
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 org.springframework.web.multipart.MultipartFile; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; public class ExcelUtils { public static int totalRows; //sheet中总行数
public static int totalCells; //每一行总单元格数
/**
* read the Excel .xlsx,.xls
* @param file jsp中的上传文件
* @return
* @throws IOException
*/
public static List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {
if(file==null||ExcelTool.EMPTY.equals(file.getOriginalFilename().trim())){
return null;
}else{
String postfix = ExcelTool.getPostfix(file.getOriginalFilename());
if(!ExcelTool.EMPTY.equals(postfix)){
if(ExcelTool.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
return readXls(file);
}else if(ExcelTool.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
return readXlsx(file);
}else{
return null;
}
}
}
return null;
}
/**
* read the Excel 2010 .xlsx
* @param file
* @return
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static List<ArrayList<String>> readXlsx(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
XSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new XSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
if(xssfSheet == null){
continue;
}
totalRows = xssfSheet.getLastRowNum();
//读取Row,从第二行开始
for(int rowNum = 0;rowNum <= totalRows;rowNum++){
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if(xssfRow!=null){
rowList = new ArrayList<String>();
totalCells = xssfRow.getLastCellNum();
//读取列,从第一列开始
for(int c=0;c<=totalCells+1;c++){
XSSFCell cell = xssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelTool.EMPTY);
continue;
}
rowList.add(ExcelTool.getXValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null; }
/**
* read the Excel 2003-2007 .xls
* @param file
* @return
* @throws IOException
*/
public static List<ArrayList<String>> readXls(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
HSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new HSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
if(hssfSheet == null){
continue;
}
totalRows = hssfSheet.getLastRowNum();
//读取Row,从第二行开始
for(int rowNum = 0;rowNum <= totalRows;rowNum++){
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if(hssfRow!=null){
rowList = new ArrayList<String>();
totalCells = hssfRow.getLastCellNum();
//读取列,从第一列开始
for(short c=0;c<=totalCells+1;c++){
HSSFCell cell = hssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelTool.EMPTY);
continue;
}
rowList.add(ExcelTool.getHValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
JAVA导入(读取)Excel中的数据(支持xls与xlsx文件)的更多相关文章
- NPOI读取Excel帮助类,支持xls与xlsx,实现公式解析,空行的处理
NPOI读取Excel(2003或者2010)返回DataTable.支持公式解析,空行处理. /// <summary>读取excel /// 默认第一行为表头 /// </sum ...
- Java利用POI导入导出Excel中的数据
首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...
- 无法读取Excel中的数据单元格。有数据,但是读出来全是空值
C#读取Excel,取值为空的解决办法! C#读取Excel遇到无法读取的解决方法是什么呢?这样在C#读取Excel的过程中有很多问题,那么本文就向你介绍如何解决C#读取Excel遇到无法读取的解决方 ...
- C# 读取Excel中的数据
#region 读取Excel中的数据 /// <summary> /// 读取Excel中的数据 /// </summary> /// <param name=&quo ...
- sql 读取excel中的数据
select 列名 as 字段名 from openBowSet('MSDASQL.1','driver=Microsoft Excel Driver(*.xls);dbq=文件存放地址','sele ...
- SpringBoot(十三)_springboot上传Excel并读取excel中的数据
今天工作中,发现同事在整理数据,通过excel上传到数据库.所以现在写了篇利用springboot读取excel中的数据的demo.至于数据的进一步处理,大家肯定有不同的应用场景,自行修改 pom文件 ...
- 读取Excel中的数据到DataSet
读取Excel中的数据到DataSet 1.引用命名空间 using System.Data.OleDb; 2.输入Excel文件,输出DataSet public DataSet ExecleDs( ...
- 用CBrother将excel中的数据转换为C语言头文件
用CBrother将excel中的数据转换为C语言头文件 最近在工作中,产品这边总是要调整一些参数,而我们在这一块要求所有的配置必须用宏定义来做,因为不同型号直接硬编码写死在代码里,但是一但数量大了, ...
- java中使用jxl读取excel中的数据
package bboss; import java.io.File; import java.io.FileInputStream; import java.io.IOException; impo ...
随机推荐
- 贪心/构造/DP 杂题选做Ⅱ
由于换了台电脑,而我的贪心 & 构造能力依然很拉跨,所以决定再开一个坑( 前传: 贪心/构造/DP 杂题选做 u1s1 我预感还有Ⅲ(欸,这不是我在多项式Ⅱ中说过的原话吗) 24. P5912 ...
- 比对软件Blast,Blast+,Diamond比较
1. Blast (1)格式化数据库 formatdb -i db.seq -p T -o T -l logfile 主要参数: -i 输入需要格式化的源数据库名称 -p 文件类型,是核苷酸序列数据库 ...
- 【Linux】非root安装Python3及其包管理
1. Python 3.8.1安装 源码安装常规操作: wget -c https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tgz tar -xv ...
- Mssql主备见证的弊端及主备模式主down掉怎么恢复
mssql主备见证有个没有解决的问题,mssql的主备是针对单个库的,有时候单个或多个库主备切换了,但是整个主数据库并没有挂掉,并且还运行着其他的库,程序检测到的数据库连接是正常的,只是部分库连接不了 ...
- [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上)
[源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 目录 [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 0x00 摘要 0x0 ...
- 【模板】无源汇有上下界可行流(网络流)/ZOJ2314
先导知识 网络最大流 题目链接 https://vjudge.net/problem/ZOJ-2314 题目大意 多组数据,第一行为数据组数 \(T\). 对于每一组数据,第一行为 \(n,m\) 表 ...
- C# js获取buttonid
var id= document.getElementById('<%=控件的ID.ClientID %>');
- Vue 之keep-alive的使用,实现页面缓存
什么是keep-alive 有时候我们不希望组件被重新渲染影响使用体验: 或者处于性能考虑,避免多次重复渲染降低性能.而是希望组件可以缓存下来,维持当前的状态.这时候就需要用到keep-alive组件 ...
- C++福尔摩斯的约会
这道题的要求总结如下: 1.DAY 星期 大写字母:A B C D E F G2.HH 时 数字+大写字母 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M ...
- Android Loader异步装载
一.Loader简介: (一).Loader的概念: 装载器从android3.0开始引进.它使得在activity或fragment中异步加载数据变得简单. 当成批显示数据的时候,为了使用户体验更好 ...