1、maven引入jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
2、测试类
package com.xd.excel;
import java.io.File;
import java.io.FileInputStream;
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;
public class TestExcel {
public static void main(String[] args) {
//读取文件,返回一个Workbook对象
Workbook wb = getExcel("D:/iotest/test.xlsx");
if(wb == null) {
System.out.println("文件读取错误!");
}else {
//解析
parseExcel(wb);
}
}
/**
* 解析Excel
* @param wb
*/
private static void parseExcel(Workbook wb) {
//解析excel
Sheet sheet = wb.getSheetAt(0);//读取sheet,从0开始
int rowNum = sheet.getLastRowNum();//读取行数,从0计数
for(int i = 0; i <= rowNum; i++) {
//获得行
Row row = sheet.getRow(i);
//获得当前行的列数
int colNum = row.getLastCellNum();
for(int j = 0; j < colNum; j++) {
//获取单元格
Cell cell = row.getCell(j);
if(cell == null) {
System.out.print("null ");
}else {
System.out.print(cell.toString()+" ");
}
}
//换行
System.out.println();
}
}
/**
* 读取Excel
* @param wb
*/
private static Workbook getExcel(String filePath) {
Workbook wb = null;
//封装文件路径
File file = new File(filePath);
//判断文件是否存在
if(!file.exists()) {
System.out.println("文件不存在!");
return wb;
}
try {
//文件存在,读取文件
InputStream is = new FileInputStream(file);
//获取文件后缀
String fileSuffix = filePath.substring(filePath.lastIndexOf("."));
//后缀是xls
if(".xls".equals(fileSuffix)) {
wb = new HSSFWorkbook(is);
}else if(".xlsx".equals(fileSuffix)) {
wb = new XSSFWorkbook(is);
}else {
System.out.println("文件格式不正确!");
}
} catch (Exception e) {
e.printStackTrace();
return wb;
}
//返回
return wb;
}
}
3、结果