一 .使用场景
工作中使用
httpservletrespose respose 请求头的编辑
String realPath = req.getSession().getServletContext().getRealPath("/WEB-INF/pages/order/");
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+ new String(("simulationSort.xlsx").getBytes(), "iso-8859-1"));
直接上代码
/** * 根据模板生成Excel文件.
* @param templateFileName 模板文件.
* @param list 模板中存放的数据.
* @param kouflist 动态部分数据
* @param response.
*/
public void createExcel(String templateFileName, List<?> list,List<Map<String, String>> kouflist,HttpServletResponse response) {
InputStream in=null;
OutputStream out=null;
// 创建XLSTransformer对象
XLSTransformer transformer = new XLSTransformer();
File f = new File(templateFileName+"/simulationSortjxls.xlsx");
String string = f.toString();
// 获取java项目编译后根路径
Map<String, Object> beanParams = new HashMap<String, Object>();
beanParams.put("list", list);
try {
in=new BufferedInputStream(new FileInputStream(string));
// 生成Excel文件 模板的静态部分已经完成
Workbook workbook = transformer.transformXLS(in, beanParams);
//设置表格的样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setWrapText(true);
//设置字体的样式
Font cellFont = workbook.createFont();
cellFont.setFontName("宋体");
cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellStyle.setFont(cellFont);
//获取表格的第一个sheet
Sheet sheet = workbook.getSheetAt(0);
//获取静态部分占啦多少行
int num = sheet.getLastRowNum();
// kouflist 是动态数据的行数信息
for (int i = 0; i < kouflist.size(); i++) {
//获取到sheet 中的第i行 kouflist.get(i)
for (int j = 0; j <kouflist.get(i).size(); j++) {
//获取到sheet 中的第i行 kouflist.get(i)中 第j列,应动态展示 该列没有,需要创建
Cell createCell = sheet.getRow(i+3).createCell(17+j);
//设置第几行中的第几列的样式
createCell.setCellStyle(cellStyle);
//给第几行中的第几列赋值
createCell.setCellValue(kouflist.get(i).get("v"+j));
}
}
//获取流
out=response.getOutputStream();
//写入 流
workbook.write(out);
//刷新
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in!=null){try {in.close();} catch (IOException e) {}}
if (out!=null){try {out.close();} catch (IOException e) {}}
}
}
未完待续......