springboot-实现excle文件导出功能

后端直接生成一个excle文件,提供给前端进行下载

1、依赖

<!-- excle操作-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.8</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.10</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
        </dependency>

2、代码

@RequestMapping(value = "/excleExport" )
    @ResponseBody
    public void csvExport(HttpServletResponse response){
        //表头
        List<String> headerList = Arrays.asList("编号", "姓名");
        //通过工具类创建writer,默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //写入表头
        writer.writeHeadRow(headerList);
        //组织数据
        // 组织数据
        List<List<Object>> data = new ArrayList<>();

        List list1 = Arrays.asList("001","张三");
        List list2 = Arrays.asList("002","李四");
        List list3 = Arrays.asList("003","王五");
        List list4 = Arrays.asList("004","王五");
        data.add(list1);
        data.add(list2);
        data.add(list3);
        data.add(list4);

        //一次性写出内容,使用默认样式,强制输出标题
        writer.write(data,true);
        //设置表格宽度自动
        writer.autoSizeColumnAll();

        //response为HttpServeltReponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        response.setHeader("Content-Disposition","attachment;filename=1.xls");
        ServletOutputStream out= null;
        try{
            out = response.getOutputStream();
            writer.flush(out,true);

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //关闭writer,释放内存
            writer.close();
        }
        IoUtil.close(out);
    }

3、post调用

 

4、下载效果

 源码获取方式(免费):
(1)登录-注册:http://resources.kittytiger.cn/
(2)签到获取积分
(3)搜索:springboot-excleExport excle文件导出

 

posted @ 2024-09-14 10:35  万笑佛  阅读(26)  评论(0编辑  收藏  举报