ExcelUtils.java
1.83 KB
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
package com.gelvshi.utils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class ExcelUtils {
//处理excel表格的工具类
public static List<Object[]> readXls(File upload) throws Exception{
FileInputStream is = new FileInputStream(upload);
Workbook wb = new XSSFWorkbook(is);
Sheet sheet = wb.getSheetAt(0);
//创建工作簿对应的表头
List<Object[]> strList = new ArrayList<>();
//看这张表总共有多少行
int lastRowNum = sheet.getLastRowNum();
try{
for (int i = 0;i<=lastRowNum;i++){
//读取到某一行
Row row = sheet.getRow(i);
//看总共有多少列
short lastCellnum = row.getLastCellNum();
//从第0个索引开始
Object[] rowData = new Object[lastCellnum];
for (int j = 0;j<lastCellnum;j++){
//拿到行其中的格子
Cell cell = row.getCell(j);
if(cell.getCellType()== HSSFCell.CELL_TYPE_STRING){
rowData[j] = cell.getStringCellValue();
}else if(cell.getCellType()== HSSFCell.CELL_TYPE_NUMERIC){
rowData[j] = cell.getNumericCellValue();
}
}
strList.add(rowData);
}
//读取数据
return strList;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}