java后台导出excel代码详细讲解

1:引入相关依赖,我用的是grodle,你们也可以去maven仓库找一下poi这个jar

    compile group: 'org.apache.poi', name: 'poi', version: '3.17'

2:写入后台代码,我用的是springmvc框架,其实这个都是无所谓的,代码简单明了,复制下来就可以拿去用,我也不做太多的介绍了,有什么不懂的可以看下注释

    /**
     *
     * @return
     * @name 导出数据
     */
    @GetMapping("exportHttp")
    public String daoChu(HttpServletResponse response){

       List<WorkEntity> list =  workService.selectAll();
        // 创建excel
        HSSFWorkbook wk = new HSSFWorkbook();
        // 创建一张工作表
        HSSFSheet sheet = wk.createSheet();
        // 2
        sheet.setColumnWidth(0, 5000);
        HSSFRow row = sheet.createRow(0);
        // 创建第一行的第一个单元格
        // 想单元格写值
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("序号");
        cell = row.createCell((short)1);
        cell.setCellValue("职位");
        cell = row.createCell((short)2);
        cell.setCellValue("早上上班时间");
        cell = row.createCell((short)3);
        cell.setCellValue("早上下班时间 ");
        cell = row.createCell((short)4);
        cell.setCellValue("下午上班时间");
        cell = row.createCell((short)5);
        cell.setCellValue("下午上班时间 ");

        // 创建第一行
        for (short i=0;i<list.size();i++)
        {
            row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(list.get(i).getWorkId());
            row.createCell(1).setCellValue(list.get(i).getPositionName());
            row.createCell(2).setCellValue(list.get(i).getAMendDate());
            row.createCell(3).setCellValue(list.get(i).getAMstartDate());
            row.createCell(4).setCellValue(list.get(i).getPMendDate());
            row.createCell(5).setCellValue(list.get(i).getPMstartDate());
        }
        try {
            /**
             * 弹出下载选择路径框
             */
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=Opinion.xls");//默认Excel名称
            response.flushBuffer();
            wk.write(response.getOutputStream());
            wk.write(new FileOutputStream(new File("D://daochu/a.xls")));
            wk.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {

        }
        return "null";
    }

3:在jsp页码触发这个方法就可以了

                     <input type="button" value="导出" class="ui_input_btn01" id="daochule" />
    <script>
        $(function () {
            $("#daochule").click(function () {
                window.location.href="exportHttp";
            })
        })
    </script>>

我jsp这样写 写的有点麻烦 你们也可以直接把button换成a标签 直接href="exportHttp" 这样就可以了  这个就是java后台导出到cxcel 有什么不懂的可以留言偶!!

原文地址:https://www.cnblogs.com/zhaoyuwei/p/9038135.html