Java 導出Excel利用模版導出

Java導出Excel和word的方式大體相同

1、Excel模版導出到頁面下載

首先,導入依賴在pom.xml中我選擇的事1.03的版本

           第二、在項目或是自己需要的地方建立個文件夾放導出文件的模版,並且配好模版

          

      第三,controller層寫入export方法,這裏我寫的沒有將可以作爲工具的部分單獨寫一塊而是直接寫在controller的方法中這樣更直觀,並且是使用註解的方式進行的項目配置

    @RequestMapping("/export")
    private void export(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,HttpServletResponse response) throws Exception {
        //根據系統的需要獲取數據源
       	List<Model> resultList = pagejson.getResults();
       	//獲得模版
		String tempFileName = request.getSession().getServletContext().getRealPath("/excelTemplate");
        //將結果放入這個list中
		List values = new ArrayList();
		Map beans = new HashMap();
		Date date = new Date();
		SimpleDateFormat simpl = new SimpleDateFormat("yyyyMMddHHmmss");
		String currntTime = simpl.format(date);
		tempFileName += "/policyDemo.xls";

		//導出列表名
		String fileName = currntTime+"列表.xls";
		values.addlist);
		beans.put("values", values);

        //文件名稱統一編碼格式
		fileName = URLEncoder.encode(fileName, "utf-8");
		
		//生成的導出文件
		File destFile = File.createTempFile(fileName, ".xls");
		
		//transformer轉到Excel
		XLSTransformer transformer = new XLSTransformer();
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
            //將數據添加到模版中生成新的文件
			transformer.transformXLS(tempFileName, beans, destFile.getAbsolutePath());
            //將文件輸入
			InputStream inputStream = new FileInputStream(destFile);
			// 設置response參數,可以打開下載頁面
			response.reset();
            //設置響應文本格式
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			//將文件輸出到頁面
            ServletOutputStream out = response.getOutputStream();
			bis = new BufferedInputStream(inputStream);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// 根據讀取並寫入
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (ParsePropertyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
            //使用完成後關閉流
			try {
				if (bis != null)
				    bis.close();
				if (bos != null)
					bos.close();
			} catch (IOException e) {
			}
		
		}
	}

如果用配置文件的方式的話response不用寫了 在配置文件那寫一下輸出類型就可以了

 

  • 第四、在頁面上做一個導出按鈕或是其他的觸發,如果想用ajax去導出的話需要做特殊處理,正常返回是不會下載的,建議用同步的方式。

	var result = $.param(queryParams);
	location.href="prolicy/export?"+result;//這裏的result則是選取的查詢條件
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章