excel格式的文件在日常编码是经常会使用,读取的过程又比较麻烦,写一个简单的工具类可以对excel中的数据进行简单的读取。
/**
* excel文件-->List
* @param excelPath excel的路径 例如:/opt/excel/xxx.xls
* @param ColumnToKey excel表格的列名->转化成返回的list中map的名字
* @param startRow 数据开始读取的行数
* @param requiredRow 必填项的行数 例如:8 就是1-8列数据是必填的
* @return 以列表的形式返回excel中每一行的数据
* @author qjx
* 说明:部分api和工具类是公司独有的,可以使用开源的工具类进行替换。
*/
public static List<Map<String, String>> parseExcelToList(String excelPath, String[] ColumnToKey, int startRow, int requiredRow) {
//获取文件名
String[] split = excelPath.split(File.separator);
String fileName = split[split.length - 1];
//判断文件名
if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
throw new BizIllegalArgumentException("路径错误:没有找到excel文件");
}
//获取流
InputStream ins;
try {
ins = new FileInputStream(excelPath);
} catch (IOException ex) {
logger.error("========内部错误:获取文件流异常!" + ex.getMessage());
throw new BizIllegalArgumentException("内部错误:获取文件流异常!");
}
Workbook wb;
try {
if (fileName.matches("^.+\\.(?i)(xls)$")) {
wb = new HSSFWorkbook(ins);
} else {
wb = new XSSFWorkbook(ins);
}
} catch (IOException ex) {
throw new BizIllegalArgumentException("内部错误:生成workbook对象出错");
}
List<Map<String, String>> retList = new ArrayList<>();
try {
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
//获取第i个sheet页的总条数
int totalRows = sheet.getPhysicalNumberOfRows();
//实际从startRow-1开始遍历行
for (int x = startRow-1; x < totalRows; x++) {
//拿到第i行数据
Row row = sheet.getRow(x);
if (row == null) {
continue;
}
Iterator<Cell> cellIterator = row.cellIterator();
int total = 0;
int emptyCount = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
total++;
if (StringUtil.nullOrEmpty(cell.toString().trim())) {
emptyCount++;
}
}
if (total == emptyCount) {
continue;
}
//行中已定义单元格的数量==0
int physicalNumberOfCells = row.getPhysicalNumberOfCells();
if (physicalNumberOfCells == 0) {
continue;
}
Map<String, String> map = new HashMap<>();
//遍历读取一行
for (int j = 0; j < physicalNumberOfCells; j++) {
Cell pocCell = row.getCell(j);
//前requiredRow列为必填项
if (j < requiredRow && StringUtil.nullOrEmpty(pocCell)) {
throw new BizIllegalArgumentException("总览文件第" + (x + 1) + "行缺少数据,请检查!");
} else if (j >= requiredRow && StringUtil.nullOrEmpty(pocCell)) {
//跳过这个单元格
continue;
}
String data = pocCell.toString().trim();
map.put(ColumnToKey[j], data);
}
retList.add(map);
}
}
} catch (Exception e) {
throw new BizIllegalArgumentException("内部错误: 解析excel文件错误!" + e.getMessage());
}
return retList;
}