2,js去下载
function download(){
var action=$("#form_apply_list").attr("action");
$("#form_apply_list").attr("action","${path}/outInfo/downLoadOutInfo.jhtml");
$("#form_apply_list").submit();
$("#form_apply_list").attr("action",action);
}
3,springmvc后台
@RequestMapping("downLoadOutInfo.jhtml")
public void downLoadGoodsInfo(HttpServletRequest request,HttpServletResponse response,
@ModelAttribute("form") OutinfoVo outinfoVo)
throws Exception{
logger.info("进入【下载出入库信息】");
outinfoVo.setIsout(Constant.IS_OUT_YES);
outinfoVo.setLoginName(getCurrentUser(request).getUserId());
//查询当前课题组下
outinfoVo.setProjectteamId(getCurrentUser(request).getCurrentPtid());
//获取分页标签数据
Page page = new Page(request.getParameter("pStart"), "1000", request.getParameter("total"));
// 调service方法
GetGoodsInfoExcel excelVo=new GetGoodsInfoExcel();
excelVo.goodsSearchInfoExcel(response, request, outinfoService.getOutinfoForPage(outinfoVo,page ),"outinfo");
}
4,生成excel并下载
//商品信息下载
public void goodsSearchInfoExcel(HttpServletResponse response,HttpServletRequest request, List<Object> list,String type) {
logger.info("进入详细下载信息的方法");
String fileName="";
String templateFileName="";
try {
if("goods".equals(type)){
fileName="goods.xls";
templateFileName="template\\goodsTemplateList.xls";
}else if("position".equals(type)){
fileName="position.xls";
templateFileName="template\\positionTemplateList.xls";
}
String filename = new Date().getTime() + fileName;
response.setHeader("Content-disposition",
"attachment; filename=" + filename);
response.setHeader("Content-Type","application/octet-stream");
response.setContentType("application/msexcel");// 定义输出类型
String rootpath =request.getSession().getServletContext().getRealPath("/");
logger.info("获取的根路径:"+rootpath);
String templateFile = rootpath +templateFileName;
logger.info("获取的模板文件的路径:templateFile="+templateFile);
// 创建文件
File file = new File(templateFile);
// 创建工作薄
Workbook wb = Workbook.getWorkbook(file);
ServletOutputStream out = response.getOutputStream();
WritableWorkbook workbook = Workbook.createWorkbook(out, wb);
WritableSheet wsheet = workbook.getSheet(0);
WritableCellFormat wcf = new WritableCellFormat();
wcf.setAlignment(Alignment.CENTRE);// 居中
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中
wcf.setWrap(true);// 自动换行
if(list!=null){
if("goods".equals(type)){
for (int i = 0; i < list.size(); i++) {
GoodsVo goodVo = (GoodsVo)list.get(i);
wsheet.addCell(new Label(0, i+1, String.valueOf(i+1)));// 序号
wsheet.addCell(new Label(1,i+1,goodVo.getGoodId()));
wsheet.addCell(new Label(2,i+1,goodVo.getProductName()));
}
}else if("position".equals(type)){
for (int i = 0; i < list.size(); i++) {
PositionVo positionVo=(PositionVo)list.get(i);
wsheet.addCell(new Label(0,i+1,String.valueOf(i+1)));
wsheet.addCell(new Label(1,i+1,positionVo.getPostionId()));
wsheet.addCell(new Label(2,i+1,positionVo.getPostion()));
}
}
}
workbook.write();
workbook.close();
wb.close();
out.close();
} catch (Exception e) {
logger.info("下载数据失败",e);
}
}