1. 程式人生 > >SpringBoot 使用POI對上傳的Excel進行處理

SpringBoot 使用POI對上傳的Excel進行處理

上一篇寫到了關於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();
        }
    }

將檔案上傳就可以執行

 

參考:https://blog.csdn.net/M_WBCG/article/details/75142807