您的位置:首页 > 编程语言 > Java开发

java后台导出excel,客户端下载

2017-03-20 17:17 351 查看
function exportFun(){
var urlDownload = '${ctx}/filemanager/termInfo/export';//请求生成excel地址
var datas = '?serial=123&airVersionName=TEST&cityName=喜乐航';
window.open(urlDownload+datas);
}
@RequestMapping("/termInfo/export")
 public void termInfoExport(TermInfo bean,String begintime,String endtime,String type,HttpServletResponse response,HttpServletRequest request) {
response.setContentType("application/msexcel;charset=UTF-8"); 
response.addHeader("Content-Disposition", "attachment;filename=\""+ new String(("export.xlsx").getBytes("GBK"), "ISO8859_1") + "\"");
OutputStream sos = null;
   sos = response.getOutputStream();
 
 XSSFWorkbook templatewb = null;
    Sheet tempSheet = null;
    int num = 1;//从第几行还是写入数据  0为第一行1为第二行
    int cellnum = 0;
//    OutputStream output =null;//文件导出流
    try {
     //output=new FileOutputStream(new File(fileName));
     //String modelName = templateName;// 获取模版
     // 获取模板
     templatewb = new XSSFWorkbook(new FileInputStream(new File(templateName)));
     tempSheet = templatewb.getSheetAt(0);//获取第一个sheet页
     //设置样式
     CellStyle style = templatewb.createCellStyle();
     // 获取模板sheet页
     style.setAlignment(HorizontalAlignment.CENTER);
     style.setVerticalAlignment(VerticalAlignment.CENTER);
     // 增加表格边框的样式 例子
     style.setBorderBottom(BorderStyle.THIN);
     style.setBorderLeft(BorderStyle.THIN);// 左边框
     style.setBorderRight(BorderStyle.THIN);// 右边框
     style.setBorderTop(BorderStyle.THIN);// 上边框
     
     Font font = templatewb.createFont();
     font.setFontName("新宋体");
     font.setFontHeightInPoints((short) 9);// 字体大小
     style.setFont(font); // 调用字体样式对象
     style.setWrapText(true);
     // 将数据写入excel
     for (int i = 0; i < dataList.size(); i++) {
      Row row = tempSheet.createRow(num++);
      row.setHeightInPoints(22); // 设置行高
      Map<String, Object> dataMap = dataList.get(i);
      cellnum = -1;
      // 排名
      Cell cellNum = row.createCell(++cellnum);
      cellNum.setCellValue(i+1);
      cellNum.setCellStyle(style);
      // 终端编号
      Cell serial = row.createCell(++cellnum);
      serial.setCellValue((String)dataMap.get("serial"));
      serial.setCellStyle(style);
      Cell mac = row.createCell(++cellnum);
      mac.setCellValue((String)dataMap.get("mac"));
      mac.setCellStyle(style);
      Cell airVersionName = row.createCell(++cellnum);
      airVersionName.setCellValue((String)dataMap.get("airVersionName"));
      airVersionName.setCellStyle(style);
      // 终端编号
      Cell cityName = row.createCell(++cellnum);
      cityName.setCellValue((String)dataMap.get("cityName"));
      cityName.setCellStyle(style);
     }
     // 将内容写入Excel
     templatewb.write(sos);
    } catch (Exception e) {
     e.printStackTrace();
    } finally {
     try {
      sos.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
    return ""; 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: