DWQA QuestionsCategory: ProgramHow does Java convert an XML type word document into a word type document
chriswong asked 4 months ago

My needs are as follows:
The word document type is XML. Open it with a text editor and see the following code (I only copied the header code)
How can Java convert it into DOC documents of word type? It seems that Apache POI can only convert word documents into XML, HTML and other formats, but not vice versa. Have you ever solved this need? Thank you first!

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage">
    <pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
        <pkg:xmlData>
            <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
                <Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
                <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
                <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
                <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml"/>
            </Relationships>
        </pkg:xmlData>
    </pkg:part>

,The general idea is to edit the word style with office2003 or 2007, then save it as XML, translate the XML into FreeMarker template, and finally use java to parse FreeMarker template and output doc. After testing, the word document generated in this way fully conforms to the office standard. The style and content control are very convenient, and the printing will not deform. The generated document is exactly the same as the edited document in office.
Use XML as the export scheme.
First create a word document, fill in a template in word according to the requirements, then change the corresponding data into variable ${}, and then save the document in XML document format. Use the document editor to open the document in XML format, remove the redundant XML symbols, read the document with FreeMarker, replace the variables, and output the word document
Freemaker jar package required
/**

  • Project Name:exam-services
  • File Name:DownloadService.java
  • Package Name:com.wt.service.download
  • Date: September 28, 2016 4:44:37 PM
  • Copyright (c) 2016, [email protected] All Rights Reserved.

*/
package com.wt.service.download;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import net.paoding.rose.web.Invocation;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
/**

  • ClassName:DownloadService <br/>
  • Function: file download< br/>
  • Reason: ADD REASON. <br/>
  • Date: September 28, 2016 4:44:37 PM < br / >
  • @author wpengfei
  • @version
  • @since JDK 1.6
  • @see

*/
@Service
public class DownloadService {

private Logger logger = Logger.getLogger(this.getClass());  

/** 
 *Download: (file download)< br/> 
 * 
 * @author wpengfei 
 * @param inv 
 * @param fileName 
 * @param path 
 * @throws IOException 
 * @since JDK 1.6 
 */  
public void downLoad(Invocation inv, String fileName, String path) throws IOException {  
      
    File file = new File(path);//  Construct the file to download  
    if (file.exists()) {  

        InputStream ins = null;  
        BufferedInputStream bins = null;  
        OutputStream outs = null;  
        BufferedOutputStream bouts = null;  

        try {  

            ins = new FileInputStream(path);//  Construct an IO stream object that reads files  
            bins = new BufferedInputStream(ins);//  Put it in the buffer stream  
            outs = inv.getResponse(). getOutputStream();//  Get file output IO stream  
            bouts = new BufferedOutputStream(outs);  
              
            String path1 = inv.getRequest().getSession().  
             getServletContext().getRealPath("/WEB-INF/downloads");  
              
            logger.info(path1);  

            inv.getResponse(). setContentType("application/x-download");//  Set the type of response content  
            inv.getResponse().setHeader("Content-disposition",  
                    "attachment;filename=" + URLEncoder. encode(fileName, "UTF-8"));//  Set header information

// inv.getResponse().setContentLength((int)file.length());

int bytesRead = 0;  
            byte[] buffer = new byte[8192];  

            //Start transferring file stream to network  
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {  

                bouts.write(buffer, 0, bytesRead);  
            }  
            bouts. flush();//  You must call the flush () method here  

        } catch (Exception e) {  

            e.printStackTrace();  
        } finally {  
            if (bouts != null) {  

                bouts.close();  
            }  
            if (outs != null) {  
                  
                outs.close();  
            }  
            if (bins != null) {  

                bins.close();  
            }  
            if (ins != null) {  

                ins.close();  
            }  
        }  
    } else {  
        logger. Info ("the exported file does not exist");  
    }  
}

}
package com.wt.common.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**

  • @Desc: word operation tool class
  • @Author:
  • @Date: January 22, 2014 05:03:19 PM

*/
public class WordUtil {

@SuppressWarnings("rawtypes")  
public static String createWord2(Map dataMap, String templateName, String filePath, String fileName) {  
    try {  
        //Create configuration instance  
        Configuration configuration = new Configuration();  

        //Set encoding  
        configuration.setDefaultEncoding("UTF-8");  

        //FTL template files are uniformly placed on COM lun. Under the template package  
        configuration.setClassForTemplateLoading(WordUtil.class, "\\com\\wt\\common\\util\\");  

        //Get template  
        Template template = configuration.getTemplate(templateName);  

        //Output file  
        File outFile = new File(filePath + File.separator + fileName);  

        //If the output destination folder does not exist, it is created  
        if (!outFile.getParentFile().exists()) {  
            outFile.getParentFile().mkdirs();  
        }  

        //Merge template and data model to generate file  
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));  

        //Generate file  
        template.process(dataMap, out);  

        //Close flow  
        out.flush();  
        out.close();  
          
        return filePath + File.separator + fileName;  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
      
    return null;  
}

}
package com.wt.controllers.test1;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.wt.common.util.CommonsUtil;
import com.wt.common.util.Constants;
import com.wt.common.util.ResponseObject;
import com.wt.common.util.WordUtil;
import com.wt.service.download.DownloadService;
/**

  • @Desc: generate word
  • @Author:
  • @Date: 2014-1-22 04:52:03 PM

*/
@Path(“/word”)
public class WordController {

@Autowired  
private DownloadService downloadService;  

private String filePath; // File path

// private String fileName; // File name

private String fileOnlyName; // File unique name  
  
  
  
/** 
 *Createword2: (the function of this method is described in one sentence here)< br/> 
 * localhost:8080/test1/word/createWord2 
 * 
 * @author wpengfei 
 * @param inv 
 * @return 
 * @throws IOException  
 * @since JDK 1.6 
 */  
@Get("/createWord2")  
public String createWord2(Invocation inv) throws IOException {  
      
    /**It is used to assemble the data required by word pages*/  
    Map<String, Object> dataMap = new HashMap<String, Object>();  
      
    Simpledateformat SDF = new simpledateformat ("MM DD, yyyy");  
      
    dataMap.put("startTime", sdf.format(new Date()));  
    dataMap.put("endTime", sdf.format(new Date()));  
    dataMap.put("count", 1);  
    dataMap.put("username", "Tom");  
    dataMap. Put ("coursename", "physical");  
    dataMap. Put ("classname", "class 1");  
    dataMap. Put ("materialname", "physical education");  
    dataMap.put("materialVer", 1.0);  
    dataMap. put("teachAim",  "Is the price of noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage Whether the 12421 price of security parity Wanfo nockel can be proud of the space avatar picking up garbage (file attachment security parity Wanfo ");  
      
    //Destination path for file export  
    filePath=Constants.UPLOAD_BASE_FOLD;  
      
    StringBuffer sb=new StringBuffer();  
    sb.append(sdf.format(new Date()));  
    sb.append("_");  
    Random r=new Random();  
    sb.append(r.nextInt(100));  
    //File unique name  
    fileOnlyName = "testDoc11_"+sb+".doc";  
      
    /**Generate word*/  
    String result = WordUtil.createWord2(dataMap, "testDoc11.ftl", filePath, fileOnlyName);  
      
    if(StringUtils.isNotBlank(result)){  
          
        downloadService.downLoad(inv, fileOnlyName, result);  
    }  
      
    return "@";  
}

},@smilesnakeFirst of all, thank you for sharing the code. It may be my problem. I didn’t describe the problem clearly. At present, I do it according to your idea, but the problem is that the doc document generated for the user is of XML type (which can be seen when saving as), and when the user opens and edits it and then saves it, it becomes a document with XML suffix, so it can’t be opened later, So my question is how to generate word type documents,This is a common problem for freemaker to generate word documents. It is essentially an XML text. You can see:http://www.xdocin.com/office&#8230;., the result is the real docx format,Has the landlord problem been solved? I also encounter this problem for advice,Has the landlord problem been solved? I also encounter this problem for advice,I also encountered this problem. Is there any good solution?,Has the landlord’s problem been solved? I also encountered this problem. Please ask the great God to teach!

joyqi replied 4 months ago

I’ll delete it if I don’t add any more

joyqi replied 4 months ago

Please use the comment function

joyqi replied 4 months ago

Questions should be put in comments, not in answers.

joyqi replied 4 months ago

@fenYes, it is executed at the terminal

joyqi replied 4 months ago

Please ignore this clause

7 Answers
smilesnake answered 4 months ago

The general idea is to edit the word style with office2003 or 2007, then save it as XML, translate the XML into FreeMarker template, and finally use java to parse FreeMarker template and output doc. After testing, the word document generated in this way fully conforms to the office standard. The style and content control are very convenient, and the printing will not deform. The generated document is exactly the same as the edited document in office.
Use XML as the export scheme.
First create a word document, fill in a template in word according to the requirements, then change the corresponding data into variable ${}, and then save the document in XML document format. Use the document editor to open the document in XML format, remove the redundant XML symbols, read the document with FreeMarker, replace the variables, and output the word document
Freemaker jar package required
/**

  • Project Name:exam-services
  • File Name:DownloadService.java
  • Package Name:com.wt.service.download
  • Date: September 28, 2016 4:44:37 PM
  • Copyright (c) 2016, [email protected] All Rights Reserved.

*/
package com.wt.service.download;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import net.paoding.rose.web.Invocation;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
/**

  • ClassName:DownloadService <br/>
  • Function: file download< br/>
  • Reason: ADD REASON. <br/>
  • Date: September 28, 2016 4:44:37 PM < br / >
  • @author wpengfei
  • @version
  • @since JDK 1.6
  • @see

*/
@Service
public class DownloadService {

private Logger logger = Logger.getLogger(this.getClass());  

/** 
 *Download: (file download)< br/> 
 * 
 * @author wpengfei 
 * @param inv 
 * @param fileName 
 * @param path 
 * @throws IOException 
 * @since JDK 1.6 
 */  
public void downLoad(Invocation inv, String fileName, String path) throws IOException {  
      
    File file = new File(path);//  Construct the file to download  
    if (file.exists()) {  

        InputStream ins = null;  
        BufferedInputStream bins = null;  
        OutputStream outs = null;  
        BufferedOutputStream bouts = null;  

        try {  

            ins = new FileInputStream(path);//  Construct an IO stream object that reads files  
            bins = new BufferedInputStream(ins);//  Put it in the buffer stream  
            outs = inv.getResponse(). getOutputStream();//  Get file output IO stream  
            bouts = new BufferedOutputStream(outs);  
              
            String path1 = inv.getRequest().getSession().  
             getServletContext().getRealPath("/WEB-INF/downloads");  
              
            logger.info(path1);  

            inv.getResponse(). setContentType("application/x-download");//  Set the type of response content  
            inv.getResponse().setHeader("Content-disposition",  
                    "attachment;filename=" + URLEncoder. encode(fileName, "UTF-8"));//  Set header information

// inv.getResponse().setContentLength((int)file.length());

int bytesRead = 0;  
            byte[] buffer = new byte[8192];  

            //Start transferring file stream to network  
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {  

                bouts.write(buffer, 0, bytesRead);  
            }  
            bouts. flush();//  You must call the flush () method here  

        } catch (Exception e) {  

            e.printStackTrace();  
        } finally {  
            if (bouts != null) {  

                bouts.close();  
            }  
            if (outs != null) {  
                  
                outs.close();  
            }  
            if (bins != null) {  

                bins.close();  
            }  
            if (ins != null) {  

                ins.close();  
            }  
        }  
    } else {  
        logger. Info ("the exported file does not exist");  
    }  
}

}
package com.wt.common.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**

  • @Desc: word operation tool class
  • @Author:
  • @Date: January 22, 2014 05:03:19 PM

*/
public class WordUtil {

@SuppressWarnings("rawtypes")  
public static String createWord2(Map dataMap, String templateName, String filePath, String fileName) {  
    try {  
        //Create configuration instance  
        Configuration configuration = new Configuration();  

        //Set encoding  
        configuration.setDefaultEncoding("UTF-8");  

        //FTL template files are uniformly placed on COM lun. Under the template package  
        configuration.setClassForTemplateLoading(WordUtil.class, "\\com\\wt\\common\\util\\");  

        //Get template  
        Template template = configuration.getTemplate(templateName);  

        //Output file  
        File outFile = new File(filePath + File.separator + fileName);  

        //If the output destination folder does not exist, it is created  
        if (!outFile.getParentFile().exists()) {  
            outFile.getParentFile().mkdirs();  
        }  

        //Merge template and data model to generate file  
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));  

        //Generate file  
        template.process(dataMap, out);  

        //Close flow  
        out.flush();  
        out.close();  
          
        return filePath + File.separator + fileName;  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
      
    return null;  
}

}
package com.wt.controllers.test1;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.wt.common.util.CommonsUtil;
import com.wt.common.util.Constants;
import com.wt.common.util.ResponseObject;
import com.wt.common.util.WordUtil;
import com.wt.service.download.DownloadService;
/**

  • @Desc: generate word
  • @Author:
  • @Date: 2014-1-22 04:52:03 PM

*/
@Path(“/word”)
public class WordController {

@Autowired  
private DownloadService downloadService;  

private String filePath; // File path

// private String fileName; // File name

private String fileOnlyName; // File unique name  
  
  
  
/** 
 *Createword2: (the function of this method is described in one sentence here)< br/> 
 * localhost:8080/test1/word/createWord2 
 * 
 * @author wpengfei 
 * @param inv 
 * @return 
 * @throws IOException  
 * @since JDK 1.6 
 */  
@Get("/createWord2")  
public String createWord2(Invocation inv) throws IOException {  
      
    /**It is used to assemble the data required by word pages*/  
    Map<String, Object> dataMap = new HashMap<String, Object>();  
      
    Simpledateformat SDF = new simpledateformat ("MM DD, yyyy");  
      
    dataMap.put("startTime", sdf.format(new Date()));  
    dataMap.put("endTime", sdf.format(new Date()));  
    dataMap.put("count", 1);  
    dataMap.put("username", "Tom");  
    dataMap. Put ("coursename", "physical");  
    dataMap. Put ("classname", "class 1");  
    dataMap. Put ("materialname", "physical education");  
    dataMap.put("materialVer", 1.0);  
    dataMap. put("teachAim",  "Is the price of noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage? Is the price of security parity Wanfo noke'er 12421 proud of the space avatar picking up garbage Whether the 12421 price of security parity Wanfo nockel can be proud of the space avatar picking up garbage (file attachment security parity Wanfo ");  
      
    //Destination path for file export  
    filePath=Constants.UPLOAD_BASE_FOLD;  
      
    StringBuffer sb=new StringBuffer();  
    sb.append(sdf.format(new Date()));  
    sb.append("_");  
    Random r=new Random();  
    sb.append(r.nextInt(100));  
    //File unique name  
    fileOnlyName = "testDoc11_"+sb+".doc";  
      
    /**Generate word*/  
    String result = WordUtil.createWord2(dataMap, "testDoc11.ftl", filePath, fileOnlyName);  
      
    if(StringUtils.isNotBlank(result)){  
          
        downloadService.downLoad(inv, fileOnlyName, result);  
    }  
      
    return "@";  
}

}

chriswong answered 4 months ago

@smilesnakeFirst of all, thank you for sharing the code. It may be my problem. I didn’t describe the problem clearly. At present, I do it according to your idea, but the problem is that the doc document generated for the user is of XML type (which can be seen when saving as), and when the user opens and edits it and then saves it, it becomes a document with XML suffix, so it can’t be opened later, So my question is how to generate word type documents

Coffee fish answered 4 months ago

This is a common problem for freemaker to generate word documents. It is essentially an XML text. You can see:http://www.xdocin.com/office&#8230;., the result is the real docx format

Happy fat house replied 4 months ago

Thank you very much, boss. I’ve been doing XML type docs all day. It can’t be parsed with POI. XDocService. It’s really hanging

shenme answered 4 months ago

Has the landlord problem been solved? I also encounter this problem for advice

Xiaocai answered 4 months ago

Has the landlord problem been solved? I also encounter this problem for advice

Millennium answered 4 months ago

I also encountered this problem. Is there any good solution?

Has the landlord’s problem been solved? I also encountered this problem. Please ask the great God to teach!