当前位置: 首页 > >

使用Hutool工具excel导出

发布时间:

这里给出个小示例


导入依赖


cn.hutool
hutool-all
5.5.4



org.apache.poi
poi-ooxml
3.17


实体类

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;


@Data
@AllArgsConstructor

public class User {
private String name;
private int age;
private Date birthday;

}

控制器层


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.jsonexer.entity.User;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class ExportController {


@GetMapping("/export")
public void exports(HttpServletResponse response){

//模拟数据
List list= new ArrayList();
list.add(new User("zhangsan",12,new Date()));
list.add(new User("zhangsan1",18,new Date()));
list.add(new User("zhangsan2",23,new Date()));
list.add(new User("zhangsan3",25,new Date()));
list.add(new User("zhangsan4",30,new Date()));
list.add(new User("zhangsan5",36, new Date()));

//通过工具类创建writer,默认创建xls格式
ExcelWriter writer = ExcelUtil.getWriter();

//自定义标题名
writer.addHeaderAlias("name","姓名");
writer.addHeaderAlias("age","年龄");
writer.addHeaderAlias("birthday","生日");

// 合并单元格后的标题行,使用默认标题样式
writer.merge(2,"申请人员信息");

//一次性写出内容,使用默认样式,强制输出标题
//Iterable data
writer.write(list,true);

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

//弹出下载对话框的文件名,不能为中文,中文请自行编码

String name = "申请学院";
try {
name = URLEncoder.encode(name,StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition","attachment;filename="+name+".xls");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

ServletOutputStream out= null;
try{
out = response.getOutputStream();
writer.flush(out,true);

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


}
}



友情链接: