通过word模板生成word文件的两种方法

1.通过poi 操作word

2.将word 变成 xml格式  然后 再使用freemark 替换掉中间的变量.然后再将文件名修改为doc就行了.

方法2有个问题是 有些格式会导致 生成的xml格式的文件打不开.

package demo;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
 
public class DocUtil {
      
       private Configuration configure = null;
      
       public DocUtil(){
              configure= new Configuration();
              configure.setDefaultEncoding("utf-8");
       }
      
       /**
        * 根据Doc模板生成word文件
        * @param dataMap Map 需要填入模板的数据
        * @param fileName 文件名称
        * @param savePath 保存路径
     * @throws IOException 
        */
       
       public static void main(String[] args) throws IOException {
    	   Map<String, String> param=new HashMap<String,String>();
    	   param.put("signComName", "signComName");
    	   param.put("contractNo", "contractNo");
    	   try {
    		   BufferedReader brReader=new BufferedReader(new FileReader(new File("c://test//contract13.xml")));
        	   BufferedWriter bwWriter=new BufferedWriter(new FileWriter(new File("c://test//contract_13.xml")));
        	   StringBuffer strBuffer=new StringBuffer();
        	  
        	   String line=null;
        	   String patternStart="</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r><w:rPr><w:rFonts w:hint=\"fareast\"/></w:rPr><w:t>";
        	   String patternEnd="</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r><w:rPr><w:rFonts w:hint=\"fareast\"/></w:rPr><w:t>";
        	   System.out.println(patternStart);
				while ((line=brReader.readLine())!=null) {
					strBuffer.append(line);
//					if (line.contains(patternStart)) {
//						System.out.println("替换开始成功");
//						line=line.replaceAll(patternStart, "");
//						
//					}
//					if (line.contains(patternEnd)) {
//						System.out.println("替换结束成功");
//						line=line.replaceAll(patternEnd, "");
//					}
					Iterator<String> it=param.keySet().iterator();
					while (it.hasNext()) {
						String key=it.next();
						 String regex = "\\$\\{[^(\\{\\})]*("+key+"){1}[^(\\{\\})]*\\}";

				    	   Pattern p1 = Pattern.compile(regex);
				           //String s ="${aacontractNbbb}$";
				           Matcher m = p1.matcher(line);
				            
				           if(m.find())
				           {
				        	   line=line.replace(m.group(), "${"+key+"}");
				               //System.out.println(m.group());
				           }
					}
					bwWriter.write(line);
					bwWriter.flush();
				}
			brReader.close();
			bwWriter.close();
			//docUtil.createDoc(dataMap, "", "");
    	   } catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	  
    	   //getContentByRegex();
       }
       public void createDoc(Map<String, Object> dataMap, String downloadType, String savePath){
              try{
                     //加载需要装填的模板
                     Template template  = null;
                     //加载模板文件
                     configure.setClassForTemplateLoading(this.getClass(),"/demo");
                     //设置对象包装器
                     configure.setObjectWrapper(new DefaultObjectWrapper());
                     //设置异常处理器
                     configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
                     //定义Template对象,注意模板类型名字与downloadType要一致
                     template= configure.getTemplate("contract3" + ".xml");
                    
                     //输出文档
                     File outFile = new File("D://result//doc//result3.doc");
                     Writer out = null;
                     out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));                                    
                     template.process(dataMap,out);
                     System.out.println("生成文档成功");
                     //outFile.delete();
              }catch (Exception e) {
                     e.printStackTrace();
              }
       }
      
       
       public static void getContentByRegex(){
    	   String a="contractNo";
    	   String regex = "\\$\\{[^\\{\\}]*("+a+"){1}[^\\{\\}]*\\}\\$";

    	   Pattern p1 = Pattern
                   .compile(regex);
           String s ="${aacontractNobbb}$";
           Matcher m = p1
                   .matcher(s);
            
           if(m.find())
           {
        	   System.out.println("ok");
        	   s=s.replace(m.group(), "${"+a+"}");
               System.out.println(s);
           }
       }
 
}

猜你喜欢

转载自fengbin2005.iteye.com/blog/2384541