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;
 }

猜你喜欢

转载自blog.csdn.net/selftranscendence/article/details/79259001