Development met today needs to be exported excel spreadsheet, select the online Ali easyExcel
line of code inside the Ali demo
/**
* 文件下载
* <p>
* 1. 创建excel对应的实体对象 参照{@link DownloadData}
* <p>
* 2. 设置返回的 参数
* <p>
* 3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
*/
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应下载的文件名不对。这个时候 请别使用swagger 他会影像
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
}
private List<DownloadData> data() {
List<DownloadData> list = new ArrayList<DownloadData>();
for (int i = 0; i < 10; i++) {
DownloadData data = new DownloadData();
data.setString("字符串" + 0);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
DownloadData objects
@Data
public class DownloadData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
}
These codes themselves then packaged into a utility class ExcelUtils
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Slf4j
public class ExcelUtils {
public static void downLoadExcel(HttpServletResponse response,Class<?> clazz,List<?> data,String fileName){
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
EasyExcel.write(response.getOutputStream(),clazz).sheet("sheet1").doWrite(data);
}catch (Exception e){
log.error("excel处理异常:" + e);
}
}
}
use
ExcelUtils.downLoadExcel(response,DownloadDTO.class,data(), “xiazai”)
The tool also has a small bug, is the filename after the Chinese can not be downloaded or become a ____. XLSX
git address
https://github.com/alibaba/easyexcel