美文网首页
SpringBoot结合poi下载excel文件

SpringBoot结合poi下载excel文件

作者: 名字已被使用咋整 | 来源:发表于2019-01-24 11:16 被阅读38次

    1.添加依赖

    <dependency> 

         <groupId>org.apache.poi</groupId>

         <artifactId>poi-ooxml</artifactId>

         <version>3.12</version>

    </dependency>

    2.创建ExcelController类

    //interviewerService是获取数据集合(excel中展示的数据)

    @Autowired

    private InterviewerServiceinterviewerService;

    @GetMapping("/getExcel")

    @ResponseBody

    public void getExcel(HttpServletResponse response) {

    //获取集合

        List<Interviewer> interviewerList =interviewerService.getInterviewer();

    HSSFWorkbook workbook =new HSSFWorkbook();

    HSSFSheet sheet = workbook.createSheet();

    int rowNum =0;

    //自定义列标题

    String[] headers ={"姓名","性别","职位"};

    HSSFRow row = sheet.createRow(rowNum);

    for (int i =0; i < headers.length; i++) {

            HSSFCell cell = row.createCell(i);

    HSSFRichTextString text =new HSSFRichTextString(headers[i]);

    cell.setCellValue(text);

    }

        for (Interviewer inter : interviewerList) {

            rowNum++;

    HSSFRow row1 = sheet.createRow(rowNum);

    row1.createCell(0).setCellValue(inter.getName());

    row1.createCell(1).setCellValue(inter.getSex());

    row1.createCell(2).setCellValue(inter.getPosition());

    }

        if (workbook !=null) {

            try {

    String fileName ="报名人员" +".xls";

    //下载后的excel名称可以为中文

    String downloadFileName =new String(fileName.getBytes("UTF-8"),"iso-8859-1");

    String headStr ="attachment; filename=\"" + downloadFileName +"\"";

    response.setContentType("APPLICATION/OCTET-STREAM");

    response.setHeader("Content-Disposition", headStr);

    OutputStream out = response.getOutputStream();

    workbook.write(out);

    } catch (IOException e) {

                e.printStackTrace();

    }

    }

    }

    相关文章

      网友评论

          本文标题:SpringBoot结合poi下载excel文件

          本文链接:https://www.haomeiwen.com/subject/mdryjqtx.html