添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
代码
package cn.cp.read;
import org.apache.poi.hssf.record.OldFormulaRecord;
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 java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
public class POIDemoOne {
/**
* 从Excel中读取数据,存储到一个集合对象中
*/
public static ArrayList<ArrayList<String>> readExcel(String filePath){
try {
// 根据文件路径,创建一个File类对象
File file = new File(filePath);
// 判断文件是否存在,会根据filePath在当前服务器磁盘上寻找文件
if (file.isFile()&&file.exists()){
// 获取文件名
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
// 获取文件前缀名
String prefix = fileName.substring(0, fileName.lastIndexOf("."));
// 获取文件后缀名
String[] split = fileName.split("\\.");
String suffix = split[split.length-1];
// 声明工作簿对象
Workbook workbook;
// 根据文件后缀名进行判断,创建工作簿对象
if ("xls".equals(suffix)){
// 创建文件输入流对象
FileInputStream fileInputStream = new FileInputStream(file);
// 创建工作簿对象
workbook = new HSSFWorkbook(fileInputStream);
}else if ("xlsx".equals(suffix)){
// 创建工作簿对象
workbook = new XSSFWorkbook(file);
}else {
System.out.println("文件类型错误,不是表格。");
return null;
}
// 创建工作表对象,读取工作簿中的工作表。假如一个工作簿中有三张工作表,则可以通过workbook.getSheetAt(i),i可以等于0、1、2
Sheet sheet = workbook.getSheetAt(0);
// 获取工作表中第一行的index
int firstRowNum = sheet.getFirstRowNum();
// 获取工作表中最后一行的index
int lastRowNum = sheet.getLastRowNum();
// 创建一个集合对象,用来存储工作表数据
ArrayList<ArrayList<String>> sheetList = new ArrayList<>();
// 遍历工作表中的行对象
for (int rowIndex = firstRowNum;rowIndex<=lastRowNum;rowIndex++){
// 创建一个集合对象,用来存储行数据
ArrayList<String> rowList = new ArrayList<>();
// 工作表根据行对象的index获取行对象
Row row = sheet.getRow(rowIndex);
// 判断行对象是否为空
if (row!=null){
// 获取行对象中第一个单元格的index
short firstCellNum = row.getFirstCellNum();
// 获取行对象中最后一个单元格的index
short lastCellNum = row.getLastCellNum();
// 遍历行对象中的单元格对象
for (int cellIndex = firstCellNum;cellIndex<=lastCellNum;cellIndex++){
// 行对象根据单元格对象的index获取单元格对象
Cell cell = row.getCell(cellIndex);
// 判断单元格对象是否为空
if (cell!=null){
// 将单元格对象添加到rowList集合对象中
rowList.add(cell.toString());
}
}
// 将rowList添加到sheetList集合对象中
sheetList.add(rowList);
}
}
// 返回sheetList工作簿集合对象
return sheetList;
}else {
System.out.println("找不到指定的文件");
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}