File file= new File(路径, 文件名称);
List<List<List<Object>>> list = ImportExcelUtils.importExcel(file);
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @Description 解析Excel工具 兼容.xls .xlsx
* @Author WangKun
* @Date 2021/1/26 17:50
* @Version
*/
public class ImportExcelUtils {
/**
* @param filePath 文件路径
* @Description 判断Excel版本
* @Throws
* @Return org.apache.poi.ss.usermodel.Workbook
* @Date 2020-07-23 18:56:29
* @Author WangKun
*/
private static Workbook readExcel(String filePath) {
if (filePath == null) {
return null;
}
String extString = filePath.substring(filePath.lastIndexOf("."));
try {
InputStream is = new FileInputStream(filePath);
if (".xls".equals(extString)) {
return new HSSFWorkbook(is);
} else if (".xlsx".equals(extString)) {
return new XSSFWorkbook(is);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param file
* @Description 文件解析
* @Throws
* @Return void
* @Date 2020-07-23 18:57:32
* @Author WangKun
*/
public static List<List<List<Object>>> importExcel(File file) {
Workbook wb;
Sheet sheet;
Row row;
wb = readExcel(file.getAbsolutePath());
if (wb != null) {
try {
List<List<List<Object>>> list = new ArrayList<>();
// 循环页签
for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
// 指定页签的值
sheet = wb.getSheetAt(sheetNum);
// 定义存放一个页签中所有数据的List
List<List<Object>> sheetList = new ArrayList<>();
// 循环行
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
// 指定行的值
row = sheet.getRow(rowNum);
// 定义存放一行数据的List
List<Object> rowList = new ArrayList<>();
// 循环列
for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
Cell cell = sheet.getRow(rowNum).getCell(cellNum);
rowList.add(getStringCellValue(cell));
}
sheetList.add(rowList);
}
list.add(sheetList);
//得到数据list
}
// 处理数据
return list;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* @param cell
* @Description 单元格格式
* @Throws
* @Return java.lang.String
* @Date 2020-07-23 18:56:54
* @Author WangKun
*/
public static String getStringCellValue(Cell cell) {
String cellvalue;
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellvalue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = cell.getDateCellValue();
cellvalue = sdf.format(date);
} else {
cellvalue = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
cellvalue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellvalue = "";
break;
default:
cellvalue = "";
break;
}
return cellvalue;
}
}