如果文件模板是固定的,直接放到服务目录下,然后可以用下面的代码下载(模板文件放到项目的webapp下,不要放到WEB-INF下)
<a target="_self" href="/template/template.xlsx" >下载office模版</a>
如果是需要从数据库查询出来导出的,则参考下面的代码
@RequestMapping(value = "/exportMatrixLeaderSheet")
public String exportMatrixLeaderSheet(HttpServletResponse response) throws IOException{
response.setHeader("Content-Disposition","attachment; filename="+new String(("联络人清单").getBytes("gb2312"),"ISO-8859-1")+".xls");
OutputStream out = response.getOutputStream();
mtxExportService.exportMatrixLeaderSheet(out);
out.close();
return null;
}
/**
* 把查询出的内控领导清单写入工作簿
* @param out
*/
public void exportMatrixLeaderSheet(OutputStream out){
HSSFWorkbook workbook = new HSSFWorkbook(); // 声明一个工作薄
HSSFSheet sheet = workbook.createSheet("联络人清单"); // 生成一个表格
sheet.setDefaultColumnWidth(20);// 设置表格默认列宽度为30个字节
HSSFRow row = sheet.createRow(0);
row.setHeight((short)(15.625*40));
HSSFCell cell = row.createCell(0);
cell.setCellStyle(getHeadCellStyle(workbook));
cell.setCellValue("单位");
cell = row.createCell(1);
cell.setCellStyle(getHeadCellStyle(workbook));
cell.setCellValue("部门(三级单位)");
cell = row.createCell(2);
cell.setCellStyle(getHeadCellStyle(workbook));
cell.setCellValue("管理员");
cell = row.createCell(3);
cell.setCellStyle(getHeadCellStyle(workbook));
cell.setCellValue("自评工作责任部门及部门经理");
cell = row.createCell(4);
cell.setCellStyle(getHeadCellStyle(workbook));
cell.setCellValue("自评工作分管领导");
HSSFCellStyle style = workbook.createCellStyle();
style.setWrapText(true);
List<MatrixLeaderSheet> mtxLeaderSheets = userInitService.getAllMtxLeaderSheet();
if(mtxLeaderSheets != null && mtxLeaderSheets.size() > 0){
int i = 1;
for(MatrixLeaderSheet mtxLeaderSheet : mtxLeaderSheets){
row = sheet.createRow(i);
row.setHeight((short)(15.625*30));
cell = row.createCell(0);
cell.setCellStyle(style);
cell.setCellValue(mtxLeaderSheet.getUnitName());
cell = row.createCell(1);
cell.setCellStyle(style);
cell.setCellValue(mtxLeaderSheet.getDepartmentName());
cell = row.createCell(2);
cell.setCellStyle(style);
cell.setCellValue(mtxLeaderSheet.getPostAdminUserName());
cell = row.createCell(3);
cell.setCellStyle(style);
cell.setCellValue(mtxLeaderSheet.getPostManagerUserName());
cell = row.createCell(4);
cell.setCellStyle(style);
cell.setCellValue(mtxLeaderSheet.getPostLeaderUserName());
i++;
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}