SpringBoot 操作Excel


SpringBoot操作excel示例

1.添加pom引用

<dependency>
  <groupId>org.apache.poigroupId>
  <artifactId>poiartifactId>
  <version>3.17version>
dependency>
<dependency>
  <groupId>org.apache.poigroupId>
  <artifactId>poi-ooxmlartifactId>
  <version>3.17version>
dependency>

2.修改maven resource 增加noFilteredFileExtension

<plugin>
  <artifactId>maven-resources-pluginartifactId>
  <configuration>
    <encoding>utf-8encoding>
    <useDefaultDelimiters>trueuseDefaultDelimiters>
    <resources>
      <resource>
        <directory>src/main/resourcesdirectory>
        <filtering>truefiltering>
      resource>
    resources>
    <nonFilteredFileExtensions>
      <nonFilteredFileExtension>xlsxnonFilteredFileExtension>
      <nonFilteredFileExtension>xlsnonFilteredFileExtension>
    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 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 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();
    }
}