excel文件上傳解析


pom文件依賴:poi處理excel文件上傳下載

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>

頁面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" th:src="@{/static/jquery-1.9.1.min.js}"></script>
    <script type="text/javascript" th:src="@{/static/jquery.ocupload-1.1.2.js}"></script>

    <script type="javascript">
        $(function () {
            $("#upload_confirm").upload({
                action: '/upload',
                name: 'file'
            });
        })

    </script>
</head>
<body>
   <form th:action="@{/upload}" enctype="multipart/form-data" th:method="post">
       上傳文件:<input type="file" name = "file">
       <input type="submit" value="提交">
   </form>
</body>
</html>

  后台接收

@RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws Exception{
        if(file == null){
            System.out.println("上傳文件為空");
        }
        System.out.println("上傳文件:00");
        updataExamineService.upload(file);
        return "成功";
    }

  service層

@Override
    public int upload(MultipartFile file) throws Exception{
        //判斷excel文件是03版本還是07版本
        String extention = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        // 獲取文件名
        String fileName = file.getOriginalFilename();
        // 獲取文件后綴
        String prefix=fileName.substring(fileName.lastIndexOf("."));
        final File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
        // MultipartFile to File
        file.transferTo(excelFile);
        //這個是07版本
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(excelFile));
        //這個是03版本
        //HSSFWorkbook  workbook2 = new HSSFWorkbook();
        //獲取文件中的表格
        Sheet sheet = workbook.getSheetAt(0);
        for(Row row : sheet){
            if(row.getRowNum() == 0){
                continue;//過濾標題行
            }
            String name = row.getCell(0).getStringCellValue();
            String code = row.getCell(1).getStringCellValue();
            Double rId = row.getCell(4).getNumericCellValue();
            Integer rId2 = rId.intValue();
            System.out.println("營銷員姓名:"+name+" ,獲取的code:"+code+",獲取的銷服人員Id:"+rId2);
 
        }

        return 0;
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM