使用apache的poi组件上传并解析excel

通过apache的poi组件解析excel,以便将数据存储到数据库中。

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
public List<String[]> paseUserStoryFile(MultipartFile file) {
List<String[]> list = new ArrayList<String[]>();
try {
POIFSFileSystem pois = new POIFSFileSystem(file.getInputStream());
//新建WorkBook
HSSFWorkbook wb = new HSSFWorkbook(pois);
//获取Sheet(工作薄)总个数
int sheetNumber = wb.getNumberOfSheets();
for (int i = 0; i < sheetNumber; i++) {
//获取Sheet(工作薄)
HSSFSheet sheet = wb.getSheetAt(i);
//开始行数
int firstRow = sheet.getFirstRowNum();
//结束行数
int lastRow = sheet.getLastRowNum();
//判断该Sheet(工作薄)是否为空
boolean isEmpty = false;
if (firstRow == lastRow) {
isEmpty = true;
}
if (!isEmpty) {
for (int j = firstRow + 1; j <= lastRow; j++) {
//获取一行
HSSFRow row = sheet.getRow(j);
//开始列数
int firstCell = row.getFirstCellNum();
//结束列数
int lastCell = row.getLastCellNum();
//判断该行是否为空
String[] value = new String[lastCell];
if (firstCell != lastCell) {
for (int k = firstCell; k < lastCell; k++) {
//获取一个单元格
HSSFCell cell = row.getCell(k);
Object str = null;
//获取单元格,值的类型
int cellType = cell.getCellType();
if (cellType == 0) {
str = cell.getNumericCellValue();
} else if (cellType == 1) {
str = cell.getStringCellValue();
} else if (cellType == 2) {
} else if (cellType == 4) {
str = cell.getBooleanCellValue();
}
value[k] = (String) str;
}
}
//每一行循环完对应的就是一个用户故事的所有属性全部拿到
list.add(value);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}