版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zc_ad/article/details/85250471
上一篇写到了关于SpringBoot 处理Excel,并对Excel进行下载处理,这次我们进行读取Excel,并对数据进行处理。
1.Maven引用
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
2.在application.yml添加以下配置
因为文件上传时在tomcat的临时文件,当过十天后,如果没有数据上传,系统会将此临时文件删除,当再次上传文件时,就会包文件夹不存在。
server:
port: 80
tomcat: ##防止报10天后,tomcat临时文件被删导致的错误
basedir: /var/log/upload/
3.contoller
@PostMapping("/salary/upload")
public Object uploadSalary(@RequestParam("file") MultipartFile file)throws Exception{
return salaryService.uploadSalary(file);
}
3.Service
public Object uploadSalary(MultipartFile file)throws Exception{
if (file.isEmpty()){
return "文件不能为空";
}
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!(suffix.equals("xlsx") || suffix.equals("xls"))){
return "请上传Excel文件";
}
analysisExcel(file.getInputStream());
return "SUCCESS";
}
/**将Ecel解析出来*/
private void analysisExcel(InputStream inputStream) throws Exception{
Workbook workbook = WorkbookFactory.create(inputStream);
inputStream.close();
Sheet sheet = workbook.getSheetAt(0); //第一个sheet
int rowLength = sheet.getLastRowNum()+1; //总行数
int colLength = sheet.getRow(0).getLastCellNum(); //总列数
//得到单元格样式
System.out.println("行数:" + rowLength + ",列数:" + colLength);
for (int i = 0; i < rowLength; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < colLength; j++) {
Cell cell = row.getCell(j);
//Excel数据Cell有不同的类型,当我们试图从一个数字类型的Cell读取出一个字符串时就有可能报异常:
//Cannot get a STRING value from a NUMERIC cell
//将所有的需要读的Cell表格设置为String格式
if (cell != null){
cell.setCellType(CellType.STRING);
System.out.print(cell.getStringCellValue() + "\t");
}
}
System.out.println();
}
}
将文件上传就可以运行