zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    display:flex 布局之 骰子
    vue 生命周期
    vue webpack 懒加载
    后台管理页面基本布局
    模拟ie9的placeholder
    常用的功能封装 pool.js
    六位数字字母验证码
    CommonJs AMD CMD
    项目封版后的总结
    jq 回到顶部
  • 原文地址:https://www.cnblogs.com/liuxm2017/p/12622440.html
Copyright © 2011-2022 走看看