1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package cn.chnmuseum.party.common.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.util.*;
public class ImportExcelUtil {
public static boolean isXls(String fileName) {
// (?i)忽略大小写
if (fileName.matches("^.+\\.(?i)(xls)$")) {
return true;
} else if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
return false;
} else {
throw new RuntimeException("格式不对");
}
}
public static List<Map<String, String>> readExcel(String fileName, InputStream is) throws Exception {
boolean ret = isXls(fileName);
Workbook workbook;
// 根据文件后缀创建不同的对象
if (ret) {
workbook = new HSSFWorkbook(is);
} else {
workbook = new XSSFWorkbook(is);
}
Sheet sheet = workbook.getSheetAt(0);
// 得到标题行
Row titleRow = sheet.getRow(0);
//行数
int lastRowNum = sheet.getLastRowNum();
//列数
int lastCellNum = titleRow.getLastCellNum();
List<Map<String, String>> list = new ArrayList<>();
for (int i = 1; i <= lastRowNum; i++) {
HashMap<String, String> map = new LinkedHashMap<>();
//获取行数据
Row row = sheet.getRow(i);
for (int j = 0; j < lastCellNum; j++) {
//获取单元格
Cell cell = row.getCell(j);
if (cell != null) {
cell.setCellType(CellType.STRING);
//cell.setCellFormula(CellType.STRING.name());
//列名 :数据
map.put(titleRow.getCell(j).getStringCellValue(), cell.getStringCellValue());
}
}
list.add(map);
}
is.close();
return list;
}
}