读取2007以上版本的excel(xslx格式)

时间:2023-03-09 02:41:43
读取2007以上版本的excel(xslx格式)

maven项目依赖jar包

    <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>

Java工具类 及main方法测试

package com.common.util.report;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; 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 ReadExcelXlsx {
public static void main(String[] args) throws IOException {
try { //传入的参数依次是:文件的位置、不需要读取的文件前几行、需要读取的文件每一行的前几个单元格
List<List<String>> list = ReadExcelXlsx.getXlslValue("D://gzzl//P020171017348216851435.xlsx", 3,3);
System.err.println(list.toString());
} catch (Exception e) {
e.printStackTrace();
}
} /**
* @param path xlsx文件的位置
* @param breakNum 读取文件的时候,不读取文件的前几行
* @param colNum 读取文件的时候读取文件的每一行的前几列
* @return
* @throws Exception
*/
public static List<List<String>> getXlslValue(String path,int breakNum,int colNum) throws Exception{
List<List<String>> allList = new ArrayList<List<String>>(); //存放整个excel
InputStream is = new FileInputStream(path);
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
// 获取每一个工作薄
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
} for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {// 获取当前工作薄的每一行
List<String> temp = new ArrayList<String>(); //每一行是一个list
if(rowNum<breakNum) { //不读取excel文件的前几行
continue;
}
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null) {
for(int m= 0;m < colNum; m++) { //读取每一行的每一个单元格
temp.add(getValue(xssfRow.getCell(m))); //getCell为读取每一个单元格,并加入list集合
}
allList.add(temp); //将读取的每一行的list 加入整个文档的list allList中存放的是整个文档数据
}
}
}
return allList;
} private static String getValue(XSSFCell xssfRow) {
if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfRow.getBooleanCellValue());
} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
return String.valueOf(xssfRow.getNumericCellValue());
} else {
return String.valueOf(xssfRow.getStringCellValue());
}
} }