使用时,前端传给后端的是base64格式的文件
public void excel(String file) {
Integer insert=-1;
//将base64转换成file文件
File base64ToFile = base64ToFile(file);
//读取文件的数据到字节流is
InputStream is = new FileInputStream(base64ToFile);
Workbook workbook = WorkbookFactory.create(is);
//读取工作表
Sheet sheet = workbook.getSheetAt(0);
//获取最后一行行号
int lastRowNum = sheet.getLastRowNum();
List<Student> peopleList=new ArrayList<>();
Map map;
//由于模板的前三行不是真正的数据,取数据时,把前三行排除
for (int i = 3; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
//当前这行全部为空时跳出本次循环
if (excel.isAllRowEmpty(row,sheet.getRow(0),(i+1))){
continue;
}
//获取当前行最后单元格列号
int lastCellNum = row.getLastCellNum();
if (lastCellNum>20){
lastCellNum=20;
}
//创建一个对象用来接收excel表中对应的数据
Student student =new Student();
map=new HashMap();
for (int j = 0; j <= lastCellNum; j++) {
//获取单元格数据
Cell cell = row.getCell(j);
String value= "";
if (cell != null) {
//这里为了去除空格和 引号 ””
row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
value = cell.getStringCellValue();
value = value.replaceAll(" ", "");
value = value.replace("\"", "");
}
map.put(j,value);
}
//将excel表里的对应的数据存进对象里
student.setName(String.valueOf(map.get(0)));
。。。。。。
}
}
依赖
<dependencies>
<!--Excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.3.0</version>
<exclusions>
<exclusion>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>