第一步:引依赖
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>1.0.5</version>
</dependency>
第二步:制作excel模板
相关语句:
${shuhao}
<jx:forEach items="${renyuans}" var="item" varStatus="s">
${item.zhengjianhaoma}
第三步:写代码
1.准备数据,放在map里吗,map的健对应的模板excel的索引。
Map<String,Object> map = new HashMap<>();
map.put("shuhao",gaochou.getShuhao());
map.put("renyuans",list);
2.渲染数据代码,参数beans即为封装的数据map。
public String saveFSWAsExcel(HttpServletRequest request, HttpServletResponse response,
Map<String,Object> beans,int num)throws Exception {
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
//模板的路径
String srcPath = courseFile.replace("\\", "/") + "...../webapp/WEB-
INF/view/excelmoban" +
"/模板1.xls";
//生成文件的路径
String to = courseFile.replace("\\", "/") + "/......../WEB-INF/view/excelmoban/人员列表.xls";
// 如果不涉及合并单元格,执行以下两句即可
// XLSTransformer transformer = new XLSTransformer();
// transformer.transformXLS(srcPath, beans, to);
// -----------------------------------------------------------
//带合并单元格代码
InputStream is = new FileInputStream(srcPath);
XLSTransformer transformer = new XLSTransformer();
HSSFWorkbook workBook = (HSSFWorkbook) transformer.transformXLS(is, beans);
HSSFSheet sheet = workBook.getSheetAt(0);
//合并单元格CellRangeAddress构造函数接收四个参数,合并行的开始,行的结束,列的开始,列
//的结束
sheet.addMergedRegion(new CellRangeAddress(4,(short)4+num-1,7,(short)7));
OutputStream os = new FileOutputStream(to);
workBook.write(os);
is.close();
os.flush();
os.close();
return to;
}