|
|
@@ -518,4 +518,75 @@ public class ExcelToolUtils {
|
|
|
}
|
|
|
return list;
|
|
|
}
|
|
|
+
|
|
|
+ public static List<Map<String,Object>> getExcelList(MultipartFile file, int startRow,List<String> excelHead)
|
|
|
+ throws Exception {
|
|
|
+ File excel = multipartFileToFile(file);
|
|
|
+ FileInputStream inputStream = null;
|
|
|
+ String fileName = excel.getName();
|
|
|
+ // 解决fileName兼容性问题
|
|
|
+ int lastindex = fileName.lastIndexOf("\\");
|
|
|
+ fileName = fileName.substring(lastindex + 1);
|
|
|
+ if (fileName != null && fileName.length() > 0) {
|
|
|
+ inputStream = new FileInputStream(excel);
|
|
|
+ }
|
|
|
+ //构建返回数组
|
|
|
+ List<Map<String,Object>> list = new ArrayList<>();
|
|
|
+ // 1. 创建工作簿
|
|
|
+ Workbook workbook = null;
|
|
|
+ // 2. 根据格式解析文件
|
|
|
+ if (fileName.endsWith(".xls")) {
|
|
|
+ workbook = new HSSFWorkbook(inputStream);
|
|
|
+ }else if(fileName.endsWith(".xlsx")){
|
|
|
+ workbook = new XSSFWorkbook(inputStream);
|
|
|
+ }else {
|
|
|
+ throw new Exception("请选择xls或者xlsx文件!");
|
|
|
+ }
|
|
|
+ for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets();sheetIndex++) {
|
|
|
+ // 获取工作表 excel分为若干个表. sheet
|
|
|
+ Sheet sheet = workbook.getSheetAt(sheetIndex);
|
|
|
+ if (sheet == null) {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ // 获取表格中最后一行的行号
|
|
|
+ int lastRowNum = sheet.getLastRowNum();
|
|
|
+ if (lastRowNum < startRow) {
|
|
|
+ throw new Exception("第"+(sheetIndex+1)+"个工作簿无数据!请检查Excel!");
|
|
|
+ }
|
|
|
+ // 定义行变量和单元格变量
|
|
|
+ Row row = null;
|
|
|
+ Cell cell = null;
|
|
|
+ //获取表头
|
|
|
+ Row titlesRow = sheet.getRow(startRow);
|
|
|
+ // 获取当前行的第一列和最后一列的标记(列数)
|
|
|
+ int firstCellNum = 0;//第一列
|
|
|
+ int lastCellNum = excelHead.size();//最后一列
|
|
|
+ try {
|
|
|
+ //遍历除表头外的所有行
|
|
|
+ for (int rowNum = startRow+1; rowNum <= lastRowNum; rowNum++) {
|
|
|
+ row = sheet.getRow(rowNum);
|
|
|
+ if(row == null){
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ //遍历行的所有列
|
|
|
+ Map<String,Object> item = new HashMap<>();
|
|
|
+ for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
|
|
|
+ cell = row.getCell(cellNum);
|
|
|
+ //获取表头对应数据
|
|
|
+ if (excelHead.get(cellNum) != null && !excelHead.get(cellNum).equals("")
|
|
|
+ && cell !=null && !cell.toString().equals("")) {
|
|
|
+ item.put(excelHead.get(cellNum),parseCell(cell));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if(item.keySet().toArray().length >0 ){
|
|
|
+ list.add(item);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ throw new Exception("文件存在隐藏行或合并列!");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return list;
|
|
|
+ }
|
|
|
}
|