hutool工具类导出Excel表格

1.引入hutool和相关依赖

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.0.7</version>
    </dependency>

    <!--必需引入下面的poi-ooxml依赖而且版本要》=3.17才行,因为Hutool工具ExcelUtil依赖这个 https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.1</version>
    </dependency>

2.创建User实体

public class User {
private String name;
private Integer age;

public User() {
}

public User(String name, Integer age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}
 

3.编写controller层

@Controller
1
public class OutputExcelController {

@RequestMapping("/export")
@ResponseBody
public void export(HttpServletResponse response) {
    List<User> list = new ArrayList<>();
    list.add(new User("zhangsan", 22));
    list.add(new User("zhangsan1", 23));
    list.add(new User("zhangsan2", 24));
    list.add(new User("zhangsan3", 25));
    list.add(new User("zhangsan4", 26));
    list.add(new User("zhangsan5", 27));
    // 通过工具类创建writer,默认创建xls格式
    ExcelWriter writer = ExcelUtil.getWriter();
    //自定义标题别名
    writer.addHeaderAlias("name", "姓名");
    writer.addHeaderAlias("age", "年龄");
    // 合并单元格后的标题行,使用默认标题样式(lastColumn应为用户属性个数-1)
    writer.merge(1, "申请人员信息");
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    //college是弹出下载对话框的文件名,不能为中文,中文请自行编码
    // String name = StringUtils.toUtf8String("学院");
    String name = "college";
    response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
    ServletOutputStream out = null;
    try {
    //out为OutputStream,需要写出到的目标流
        out = response.getOutputStream();
        writer.flush(out, true);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
// 关闭writer,释放内存
        writer.close();
    }
//此处记得关闭输出Servlet流
    IoUtil.close(out);
}
}

4.编写前端页面来访问export接口导出Excel表格
templates下创建一个export.html在body里通过一个超链接“导出Excel”去访问后端的export接口导出Excel表格(直接在浏览器输入接口地址也能导出Excel表)
 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值