java导出word带图片之后台

来源:互联网 发布:关于ai人工智能的书籍 编辑:程序博客网 时间:2024/04/28 15:29
@Action(value="/export-exportDiagram",results={/*@Result(name="getAllRule",location="/rule_list.jsp")*/})public void exportDiagram() throws ParseException, TemplateNotFoundException, MalformedTemplateNameException, freemarker.core.ParseException, IOException{ExportWordAction e1 =new ExportWordAction();String jsondata1=java.net.URLDecoder.decode(jsondata,"utf-8");ifFirefox=java.net.URLDecoder.decode(ifFirefox,"utf-8");path=java.net.URLDecoder.decode(path,"utf-8");//System.out.println("jsondata1:"+jsondata1);//System.out.println("ifFirefox1:"+ifFirefox+"     path1:"+path);JSONObject json = JSONObject.parseObject(jsondata1);String startTime = json.getString("startTime");String endTime = json.getString("endTime");//String pm25ValueAndSTD = json.getString("pm25ValueAndSTD");String familyValueAndSTD = json.getString("familyValueAndSTD");String officeValueAndSTD = json.getString("officeValueAndSTD");String outValueAndSTD = json.getString("outValueAndSTD");String objectName = json.getString("objName");SimpleDateFormat sdf  =   new  SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); Calendar cal=Calendar.getInstance();Date startDate = sdf.parse( startTime );cal.setTime(startDate);int startYear = cal.get(Calendar.YEAR);    //获取年    int startMonth = cal.get(Calendar.MONTH) + 1;   //获取月份,0表示1月份int startDay = cal.get(Calendar.DAY_OF_MONTH);    //获取当前天数Date endDate = sdf.parse(endTime);cal.setTime(endDate);int endYear = cal.get(Calendar.YEAR);    //获取年    int endMonth = cal.get(Calendar.MONTH) + 1;   //获取月份,0表示1月份int endDay = cal.get(Calendar.DAY_OF_MONTH);    //获取当前天数//获取系统时间cal.setTime(new Date());int sysYear = cal.get(Calendar.YEAR);int sysMonth = cal.get(Calendar.MONTH) + 1;int sysDay = cal.get(Calendar.DAY_OF_MONTH);Map<String, Object> map = new HashMap<String, Object>();//对应word中占位符的变量名map.put("objectName",objectName);map.put("alltime",startYear+"年"+startMonth+"月"+startDay+"日~"+endYear+"年"+endMonth+"月"+endDay+"日");map.put("porttime",startMonth+"月"+startDay+"日~"+endMonth+"月"+endDay+"日");map.put("familyValueAndSTD", familyValueAndSTD);map.put("officeValueAndSTD", officeValueAndSTD);map.put("outValueAndSTD", outValueAndSTD);map.put("sysTime", sysYear+"年"+sysMonth+"月"+sysDay+"日");//读取图片        map.put("pm25avgmap", getImageStr(path+"/pm25avgmap.png"));        map.put("famiOffOutmap", getImageStr(path+"/famiOffOutmap.png"));               String rootPath = ExportWordAction.class.getResource("").getFile();         Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);        cfg.setDirectoryForTemplateLoading(new File(URLDecoder.decode(rootPath,"utf-8")+"docTemplate/"));                cfg.setDefaultEncoding("UTF-8");               cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);                // 获取模板        Template t = cfg.getTemplate("doc.ftl");               // configuration.setClassForTemplateLoading(e1.getClass(), "/docTemplate/");//Template t = configuration.getTemplate("doc.ftl");OutputStream outputStream = null;OutputStreamWriter oWriter = null;Writer out = null;  try {outputStream = new BufferedOutputStream(response.getOutputStream());  String fName="居民个体暴露监测结果(PM2.5)反馈单.doc";if(ifFirefox=="1" || ifFirefox.equals("1")){//是火狐浏览器fName = new String(fName.getBytes("GB2312"),"ISO-8859-1");}else{fName = URLEncoder.encode(fName, "UTF-8"); //必须 否则 中文乱码,无法下载回源文件}//fName = URLEncoder.encode(fName, "UTF-8"); //必须 否则 中文乱码,无法下载回源文件response.reset();  response.setHeader("Content-Disposition", "attachment; filename=\"" + fName + "\"");        oWriter = new OutputStreamWriter(outputStream,"UTF-8");          //这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。          //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));          out = new BufferedWriter(oWriter);   t.process(map, out);} catch (Exception e) {e.printStackTrace();}finally{if(outputStream!=null)outputStream.flush();outputStream.close();if(oWriter!=null)oWriter.flush();oWriter.close();if(out!=null){out.close();deleteDirectory(path);//报告导出完成,删除临时文件夹}}//return NONE;}


 function downloadDOC(data){//alert("火狐");var ifFirefox = "0";//是否是火狐浏览器  1:是0:否if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){     ifFirefox = "1";}  window.location=encodeURI(encodeURI('export-exportDiagram?jsondata='+jsondata+'&ifFirefox='+ifFirefox+'&path='+data));//window.location="./export-exportDiagram?jsondata="+jsondata+"&ifFirefox="+ifFirefox+"&path="+data;MoveRunningDiv();} 



获取图片流



/**
* 获取图片流
* @param path
* @return
*/
private String getImageStr(String path) {
String imgFile = path;
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}



/**
* 删除文件夹及文件夹下的文件
* @param sPath 文件路径
* @return
*/
public boolean deleteDirectory(String sPath) { 
boolean flag = false;  
  //如果sPath不以文件分隔符结尾,自动添加文件分隔符  
  if (!sPath.endsWith(File.separator)) {  
      sPath = sPath + File.separator;  
   }  
   File dirFile = new File(sPath);  
   //如果dir对应的文件不存在,或者不是一个目录,则退出  
   if (!dirFile.exists() || !dirFile.isDirectory()) {  
       return false;  
   }  
   flag = true;  
   //删除文件夹下的所有文件(包括子目录)  
   File[] files = dirFile.listFiles();  
   for (int i = 0; i < files.length; i++) {  
       //删除子文件  
       if (files[i].isFile()) {  
           flag = deleteFile(files[i].getAbsolutePath());  
           if (!flag) break;  
       } //删除子目录  
       else {  
           flag = deleteDirectory(files[i].getAbsolutePath());  
           if (!flag) break;  
       }  
   }  
   if (!flag) return false;  
   //删除当前目录  
   if (dirFile.delete()) {  
       return true;  
   } else {  
       return false;  
   }  



/** 
* 删除单个文件 
* @param   sPath    被删除文件的文件名 
* @return 单个文件删除成功返回true,否则返回false 
*/  
public static boolean deleteFile(String sPath) {  
boolean flag = false;  
File file = new File(sPath);  
  // 路径为文件且不为空则进行删除  
   if (file.isFile() && file.exists()) {  
       file.delete();  
       flag = true;  
   } 
   return flag;  
}

原创粉丝点击