需要的maven依赖包:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
代码如下:
package com.demo.drools.test;
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 javax.servlet.ServletException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Testpoi{
public static void doPost() throws ServletException, IOException {
//excel文件路径
//String excelPath = "C:\\Users\\yjq\\Desktop\\1.xls";
String excelPath = "C:\\Users\\yjq\\Desktop\\2.xlsx";
try {
File excel = new File(excelPath);
//判断文件是否存在
if (excel.isFile() && excel.exists()) {
//.是特殊字符,需要转义!!!!!
String[] split = excel.getName().split("\\.");
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(split[1])){
//文件流对象
FileInputStream fis = new FileInputStream(excel);
wb = new HSSFWorkbook(fis);
}else if ("xlsx".equals(split[1])){
wb = new XSSFWorkbook(excel);
}else {
System.out.println("文件类型错误!");
return;
}
//开始解析
//获取所以的sheet页
int numberOfSheets = wb.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = wb.getSheetAt(i);
//读取第一行和最后一行
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
System.out.println("firstRowIndex: "+firstRowIndex);
System.out.println("lastRowIndex: "+lastRowIndex);
//遍历行
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
//遍历列
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
Cell cell = row.getCell(cIndex);
if (cell != null) {
System.out.println(cell.toString());
}
}
}
}
}
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws ServletException, IOException {
doPost();
}
}