直接上代码
@GetMapping("/exportOrder")
public void exportOrderXlsx(HttpServletResponse response) throws IOException {
List<OrderEntity> list = orderService.list();
// 通过工具类创建writer,默认创建xls格式
ExcelWriter writer = ExcelUtil.getWriter();
//创建xlsx格式的
//ExcelWriter writer = ExcelUtil.getWriter(true);
//自定义标题别名
writer.addHeaderAlias("orderno", "订单号");
writer.addHeaderAlias("carno", "车牌号");
writer.addHeaderAlias("paytime", "支付时间");
writer.addHeaderAlias("amount", "订单金额");
writer.addHeaderAlias("payuseropenid", "支付人");
//设置单元格宽度
int[] arr = {30, 30, 25, 10};
for (int i = 0; i < arr.length; i++) {
writer.setColumnWidth(i, arr[i]);
}
// 合并单元格后的标题行,使用默认标题样式,从0开始
writer.merge(4, "订单记录");
//只导出有别名的字段
writer.setOnlyAlias(true);
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
String excelName = "订单记录";
//response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
response.setHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes("utf-8"), "ISO-8859-1") + ".xls");
ServletOutputStream out=response.getOutputStream();
writer.flush(out, true);
// 关闭writer,释放内存
writer.close();
//此处记得关闭输出Servlet流
IoUtil.close(out);
}