Two ways to generate word files from word templates

1. Operate word through poi

 

2. Change word into xml format and then use freemark to replace the variable in the middle. Then change the file name to doc.

The problem with method 2 is that some formats will cause the generated xml format file to not be opened.

 

 

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");
       }
      
       /**
        * Generate word files based on Doc templates
        * @param dataMap Map The data that needs to be filled in the template
        * @param fileName file name
        * @param savePath save path
     * @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("Replacement started successfully");
//						line=line.replaceAll(patternStart, "");
//						
//					}
//					if (line.contains(patternEnd)) {
// System.out.println("Replacement completed successfully");
//						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}$";
				           Matches 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{
                     //Load the template that needs to be loaded
                     Template template  = null;
                     //load template file
                     configure.setClassForTemplateLoading(this.getClass(),"/demo");
                     // set the object wrapper
                     configure.setObjectWrapper(new DefaultObjectWrapper());
                     //set exception handler
                     configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
                     //Define the Template object, note that the template type name should be consistent with downloadType
                     template= configure.getTemplate("contract3" + ".xml");
                    
                     // output document
                     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("The document was generated successfully");
                     //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);
           }
       }
 
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326564803&siteId=291194637