1. 程式人生 > >java匯出word文件

java匯出word文件

//頁面點選按鈕

function dc(id){

$.ajax({
type : "post",
url : "/member/word",
async: false,
data: {id:id},
success : function(data){
            if(data.status=="0"){
            window.location.href="/member/downloadYy?name="+data.name+"&url="+data.url;
            }
            }
});

//後臺封裝好word資料

@RequestMapping(value="/word")
@ResponseBody
public Map<String,String> word(Integer id){
//String rootPath = Constant.UPLOAD_HOS;//測試路徑
String rootPath = "D://files/upload/yycase";
//String rootPath = Constant.UPLOAD_HOS_DIR;
File realPathFile = new File(rootPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
Map<String,String> map = new HashMap<String, String>(); 
   Map<String,Object> dataMap=new HashMap<String,Object>();
   Cases cases = casesService.findOne(id);
   getData(dataMap,cases);
   Configuration  configuration = new Configuration();  
        configuration.setDefaultEncoding("UTF-8");  

  configuration.setClassForTemplateLoading(this.getClass(), "/");//模板檔案所在路徑
   Template t=null; 
   try { 
     t = configuration.getTemplate("mubb.ftl"); //獲取模板檔案
   } catch (IOException e) { 
     e.printStackTrace(); 
   }
   String name = "doc_"+Math.random()*10000+".doc";
   //String url = Constant.UPLOAD_HOS_DIR+"/"+name;
   //String url = Constant.UPLOAD_HOS+"/"+name;//測試路徑
   String url = "D://files/upload/yycase"+"/"+name;
   File outFile = new File(url); //匯出檔案
   Writer out = null; 
   try { 
     out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
   } catch (FileNotFoundException e1) { 
     e1.printStackTrace(); 
   } catch (UnsupportedEncodingException e) {
e.printStackTrace();

      
   try { 
     t.process(dataMap, out); //將填充資料填入模板檔案並輸出到目標檔案 
     map.put("name", name);
     map.put("url", url);
     map.put("status", "0");
     return map;
 } catch (TemplateException e) { 
     e.printStackTrace();
   } catch (Exception e) { 
     e.printStackTrace(); 
   }finally{
   try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
   }
   return map;

}

//給模板填充資料(這只是個例子)

word文件的模板是先建立一個word文件,然後自己寫一個模板出來,另存為xml,之後重新命名成ftl。

在ftl檔案裡面找到要新增動態資料的地方,用${name}。這樣生成出來的資料就是你給這個name的值。

就是dataMap.put("name","yisheng")。name的值就是yisheng。


private void getData(Map<String, Object> dataMap,Cases cases) {
 //step5之前不用驗證step是否為空,因為沒走到step5不能入組
 //step1
 dataMap.put("procedureDate", cases.getStep1().getProcedureDate()==null?" ":cases.getStep1().getProcedureDate().toString().substring(0, 10));
 dataMap.put("sex", cases.getStep1().getSex()==null?" ":cases.getStep1().getSex()); 
 dataMap.put("age", cases.getStep1().getAge()==null?" ":cases.getStep1().getAge()); 
 dataMap.put("symptoms", cases.getStep1().getSymptoms()==null?" ":cases.getStep1().getSymptoms().substring(1, cases.getStep1().getSymptoms().length()-1)); 
 dataMap.put("birthday", cases.getStep1().getBirthday()==null?" ":cases.getStep1().getBirthday().toString().substring(0, 10)); 
 dataMap.put("centerName", cases.getStep1().getCenterName()==null?" ":cases.getStep1().getCenterName()); 
 dataMap.put("hospitalNumber", cases.getStep1().getHospitalNumber()==null?" ":cases.getStep1().getHospitalNumber()); 
 dataMap.put("realName", cases.getStep1().getRealName()==null?" ":cases.getStep1().getRealName()); 

}

//最後下載word文件

 @RequestMapping(value="/downloadYy")
 @ResponseBody
 public String downloadYy(HttpServletRequest request, HttpServletResponse response,String name,String url) {
 String rootPath = url;
 if (rootPath != null) {
 File file = new File(rootPath);
 if (file.exists()) {
 String fileName=name;
 response.setContentType("application/force-download");// 設定強制下載不開啟
 try {
 response.addHeader("Content-Disposition","attachment;fileName=" +  new String(fileName.getBytes(), "ISO-8859-1"));
 } catch (UnsupportedEncodingException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }// 設定檔名
 byte[] buffer = new byte[1024];
 FileInputStream fis = null;
 BufferedInputStream bis = null;
 try {
 fis = new FileInputStream(file);
 bis = new BufferedInputStream(fis);
 OutputStream os = response.getOutputStream();
 int i = bis.read(buffer);
 while (i != -1) {
 os.write(buffer, 0, i);
 i = bis.read(buffer);
 }
 } catch (Exception e) {
 // TODO: handle exception
 e.printStackTrace();
 } finally {
 if (fis != null) {
 try {
 fis.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
 }
 }
 return null;
 }