SpringBoot 操作Excel


SpringBoot操作excel示例

1.添加pom引用

<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.修改maven resource 增加noFilteredFileExtension

<plugin>
  <artifactId>maven-resources-plugin</artifactId>
  <configuration>
    <encoding>utf-8</encoding>
    <useDefaultDelimiters>true</useDefaultDelimiters>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    <nonFilteredFileExtensions>
      <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
      <nonFilteredFileExtension>xls</nonFilteredFileExtension>
    </nonFilteredFileExtensions>
  </configuration>
</plugin>

3.導出excel

直接瀏覽器訪問地址就可以下載

@Controller
@RequestMapping("/export")
public class ExcelController{
    @ApiOperation(value = "excel報表示例", httpMethod = "GET")
    @RequestMapping(value = "/reportDemo", method = RequestMethod.GET)
    public Object reportDemo(@RequestParam(value = "year", required = false) String year) throws UnsupportedEncodingException {

        if (StringUtils.isEmpty(year)) {
            year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR) - 1);
        }

        List<ApplyFormGroupByAreaNameVo> list = reportMapper.applyGroupByAreaName(year);

        String filename = "機構統計表.xlsx";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment;filename=", URLEncoder.encode(filename, "utf-8"));
        // application/octet-stream : 二進制流數據(最常見的文件下載)。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {
            return new ResponseEntity<byte[]>(writeApplygroupbyToExcel(list), headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    public byte[] writeApplygroupbyToExcel(List<ApplyFormGroupByAreaNameVo> data) throws IOException {
        // 打包后Spring試圖訪問文件系統路徑,但無法訪問JAR中的路徑。 因此必須使用resource.getInputStream()
        try (InputStream in = new FileInputStream(new File("D:/template/機構統計表.xlsx"))) {  //發布時使用
            //try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("申報人信息明細表.xlsx")) { //測試使用
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheet("Sheet1");

            for (int i = 0; i < data.size(); i++) {
                ApplyFormGroupByAreaNameVo item = data.get(i);
                int newRowIndex = sheet.getLastRowNum() + 1;
                XSSFRow newRow = sheet.createRow(newRowIndex);
                int cellIndex = 0;
                newRow.createCell(cellIndex++, CellType.STRING).setCellValue(String.valueOf((i + 1)));
                newRow.createCell(cellIndex++, CellType.STRING).setCellValue(item.getArea_name());
                newRow.createCell(cellIndex++, CellType.STRING).setCellValue(item.getCount());
            }

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            workbook.write(output);
            workbook.close();
            return output.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }
}

4.導入excel 

@Controller
@RequestMapping("/import")
public class ExcelController{

    @RequestMapping(value = "/data", method = RequestMethod.POST)
    public String dataImport(@RequestParam("file") MultipartFile file) {

        try {

            importData(file.getInputStream());

            return "ok";

        } catch (Exception e) {
            return "err";
        }

    }
    
    //操作數據
    private void importData(InputStream in) throws IOException {

        XSSFWorkbook workbook = new XSSFWorkbook(in);
        in.close();
        //讀取第一個sheet
        XSSFSheet sheet = workbook.getSheetAt(0);
        //從第3行讀取到最后一行
        for (int rowIndex = 3; rowIndex <= sheet.getLastRowNum(); rowIndex++) {

            // XSSFRow 代表一行數據
            XSSFRow row = sheet.getRow(rowIndex);
            //獲取單元格信息
            XSSFCell dateCell = row.getCell(0)
        }
        // 操作完畢后,記得要將打開的 XSSFWorkbook 關閉
        workbook.close();
    }
}


免責聲明!

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



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