Update ExportExcelServlet.java

pull/1/head
pght2c95q 8 months ago
parent 77c4177bf0
commit 7bfcf69c25

@ -24,34 +24,35 @@ import cn.hutool.poi.excel.StyleSet;
/** /**
* *
* @ClassName: ExportExcelServlet * @ClassName: ExportExcelServlet
* @Description: excel * @Description: excel
* @author: ljy * @author: ljy
* @date: 20191124 2:04:49 * @date: 20191124 2:04:49
*/ */
public class ExportExcelServlet extends HttpServlet { public class ExportExcelServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/**
* GETExcel
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws ServletException Servlet
* @throws IOException IO
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 从数据库中拉取数据 // 从数据库中拉取数据
PrepService prepService = new PrepServiceImpl(); PrepService prepService = new PrepServiceImpl();
List<Prep> rows = prepService.getAll(); List<Prep> rows = prepService.getAll();
// 通过工具类创建writer // 通过工具类创建writer
ExcelWriter writer = ExcelUtil.getWriter(); ExcelWriter writer = ExcelUtil.getWriter();
// 设置单元格样式
// 设置单元格样式 (好像没用,待修复)
StyleSet style = writer.getStyleSet(); StyleSet style = writer.getStyleSet();
CellStyle cellStyle = style.getHeadCellStyle(); CellStyle cellStyle = style.getHeadCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
cellStyle.setShrinkToFit(true); //设置单元格列宽自适应 cellStyle.setShrinkToFit(true); //设置单元格列宽自适应
cellStyle.setDataFormat((short) 2); cellStyle.setDataFormat((short) 2);
//自定义标题别名 //自定义标题别名
writer.addHeaderAlias("prepId", "订单ID"); writer.addHeaderAlias("prepId", "订单ID");
writer.addHeaderAlias("trainId", "车次ID"); writer.addHeaderAlias("trainId", "车次ID");
@ -70,23 +71,17 @@ public class ExportExcelServlet extends HttpServlet {
// 一次性写出内容,使用默认样式,强制输出标题 // 一次性写出内容,使用默认样式,强制输出标题
writer.write(rows, true); writer.write(rows, true);
//out为OutputStream需要写出到的目标流 // 设置响应的内容类型为Excel文件
//response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名不能为中文中文请自行编码 // 设置响应头,提示浏览器这是一个附件,需要下载
response.setHeader("Content-Disposition","attachment;filename=preps.xls"); response.setHeader("Content-Disposition","attachment;filename=preps.xls");
ServletOutputStream out=response.getOutputStream(); ServletOutputStream out = response.getOutputStream();
// 将Excel写入到输出流
writer.flush(out, true); writer.flush(out, true);
// 关闭writer释放内存 // 关闭writer释放内存
writer.close(); writer.close();
//此处记得关闭输出Servlet // 关闭输出
IoUtil.close(out); IoUtil.close(out);
} }
} }
Loading…
Cancel
Save