您的位置:首页 > 其它

POI导出Excel文件,浏览器点击可下载

2018-01-17 15:16 399 查看

说明:使用SpringMVC+POI

1:服务端代码

/**
* 导出日志查询列表
*/
@RequestMapping(value = "/log_excel")
public void exportLogList(HttpServletRequest request, OperationLog vo, @RequestParam(value = "pageNo", required = false) Integer pageNo,HttpServletResponse response) throws CodeException {
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("日志信息列表");
HSSFRow headRow = sheet.createRow(0);

//这是一些要导出列的标题
String[] title = new String[] { "ID","操作时间"};
for (int i = 0; i < title.length; i++) {
headRow.createCell(i).setCellValue(title[i]);
}
//要导出的数据对象集合
List<OperationLog> list = page.getBeans();
if (list != null && list.size() > 0) {
for (OperationLog log : list) {
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
this.setCellStyle(workbook,dataRow.createCell(0),log.getId());
this.setCellStyle(workbook,dataRow.createCell(1),new SimpleDateFormat("yyyy-MM-dd").format(log.getCreateTime()));
}
}
sheet.autoSizeColumn(1, true);
//对象置空
list = null;
response.reset();
response.setContentType("application/ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("日志信息列表.xls", "UTF-8"))));
try {
workbook.write(response.getOutputStream());
response.getOutputStream().flush();
} catch (Exception e) {
sysLog.error("日志列表Excel导出出错", e);
throw e;
}finally{
if(workbook!=null){
workbook.close();
}
if(response.getOutputStream()!=null){
response.getOutputStream().close();
}
}
} catch (CodeException ce) {
sysLog.error("日志列表Excel导出出错", ce);
throw ce;
} catch (Exception e) {
sysLog.error("日志列表Excel导出出现系统错误", e);
throw new CodeException(CodeConstants.SYS_ERROR, new Object[] { "日志列表Excel导出出现系统错误" }, e);
}
}
public HSSFCell setCellStyle(HSSFWorkbook workbook,HSSFCell cell,String value){
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
cellStyle.setDataFormat(format.getFormat("@"));
cell.setCellStyle(cellStyle);
cell.setCellValue(value);
return cell;
}


浏览器请求代码

//当点击下面元素的时候,请求该映射路径,然后就会弹出下载框
$("#QueryExcel").click(function(){
$("#QueryForm").attr("action","${root}/logManagement/001/log_excel.do");
$("#QueryForm").submit();
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐