码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot 操作Excel

时间:2020-04-02 19:32:24      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:操作   excel   ram   cell   单元格   inpu   print   stat   发布   

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();
    }
}

SpringBoot 操作Excel

标签:操作   excel   ram   cell   单元格   inpu   print   stat   发布   

原文地址:https://www.cnblogs.com/liuxm2017/p/12622440.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!