SpringBoot+hutool工具-数据库数据导出Excel

hutool文档地址:https://www.hutool.cn/docs/#/

导入依赖

	<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.0.M2</version>
        </dependency>
		
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.0.0</version>
        </dependency>

        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.12.2</version>
        </dependency>

测试例子(写入excel文件):

@SpringBootTest
class Demo1ApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        List<SysUser> users = userMapper.getUsers();

//        通过工具创建writer对象
//        ExcelWriter writer = ExcelUtil.getWriter();
//        通过构造方法创建对象
        ExcelWriter writer = new ExcelWriter("D:\\test.xls");
//        跳过第一行
        writer.passCurrentRow();
//        合并单元格作标题行
        writer.merge(3,“测试标题”);
//        一次性写出内容
        writer.write(users, true);
//        关闭writer
        writer.close();
    }
}

官网例子:https://www.hutool.cn/docs/#/poi/Excel生成-ExcelWriter?id=使用例子

导出到客户端下载

    @GetMapping("/export")
    public String exportExcel(HttpServletResponse response) throws IOException {
        List<SysUser> users = userService.getUsers();

        // 通过工具类创建writer,默认创建xls格式,若想生成xlsx格式,请使用ExcelUtil.getWriter(true)创建
        //ExcelWriter writer = ExcelUtil.getWriter();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 一次性写出内容,使用默认样式,强制输出标题
        writer.write(users, true);

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //test.xlsx是弹出下载对话框的文件名,不能为中文,中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer,释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
        return "export";
    }
posted @ 2022-04-12 16:09  Comfortable  阅读(434)  评论(0编辑  收藏  举报