How java converts word documents of type xml to documents of type word

my requirements are like this:
word document type is xml, open with a text editor to see the following code (I only copied the header part of the code)
how java can convert it to word type doc documents, Apache"s poi seems to only convert word documents into xml, html and other formats, but not vice versa. I would like to ask if there are any friends who have solved this need, thank you in advance!

<?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>
Mar.12,2021

The general idea of

is to edit the style of word with office2003 or 2007, then save as xml, translate xml into FreeMarker template, and finally use java to parse the FreeMarker template and output Doc. After testing, the word document generated in this way is fully in line with the office standard, the style and content control is very convenient, the print will not be deformed, and the generated document is exactly the same as the document edited in office.
use xml as the export scheme.

first create a word document, fill in a template in word as required, then change the corresponding data into the variable ${}, then save the document in xml document format, open the document in xml format using a document editor, remove the extra xml symbols, read the document with Freemarker and replace the variables, and output the word document

freemarker jar package is required

/ *

  • Project Name:exam-services
  • File Name:DownloadService.java
  • Package Name:com.wt.service.download
  • Date: 4:44:37 on September 28th, 2016
  • Copyright (c) 2016, chenzhou1025@126.com 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/ >
  • download the Function: file. < br/ >
  • Reason: ADD REASON. < br/ >
  • Date: 4:44:37 on September 28th, 2016 < br/ >
  • @ author wpengfei
  • @ version
  • @ since JDK 1.6
  • @ see

* /
@ Service
public class DownloadService {

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

/** 
 * 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);//   
    if (file.exists()) {  

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

        try {  

            ins = new FileInputStream(path);// IO  
            bins = new BufferedInputStream(ins);//   
            outs = inv.getResponse().getOutputStream();// IO  
            bouts = new BufferedOutputStream(outs);  
              
            String path1 = inv.getRequest().getSession().  
             getServletContext().getRealPath("/WEB-INF/downloads");  
              
            logger.info(path1);  

            inv.getResponse().setContentType("application/x-download");// response  
            inv.getResponse().setHeader("Content-disposition",  
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//   

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

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

            //   
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {  

                bouts.write(buffer, 0, bytesRead);  
            }  
            bouts.flush();// flush()  

        } 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("");  
    }  
}  
  
  
  
  

}

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 manipulation tool class
  • @ Author:
  • @ Date:2014-1-22 05:03:19 p.m.

* /
public class WordUtil {

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

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

        // ftl com.lun.template   
        configuration.setClassForTemplateLoading(WordUtil.class, "\\com\\wt\\common\\util\\");  

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

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

        //   
        if (!outFile.getParentFile().exists()) {  
            outFile.getParentFile().mkdirs();  
        }  

        //   
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));  

        //   
        template.process(dataMap, out);  

        //   
        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: generates word
  • @ Author:
  • @ Date:2014-1-22 04:52:03 p.m.

* /
@ Path (https://api-v5.segmentfault.com/question/"/ word")
public class WordController {

  
@Autowired  
private DownloadService downloadService;  

private String filePath; //  

/ / private String fileName; / / File name

private String fileOnlyName; //  
  
  
  
/** 
 * createWord2:(). <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 {  
      
    /** word */  
    Map<String, Object> dataMap = new HashMap<String, Object>();  
      
    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");  
      
    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", "");  
    dataMap.put("className", "1");  
    dataMap.put("materialName", "");  
    dataMap.put("materialVer", 1.0);  
    dataMap.put("teachAim", "1242112421124211242112421");  
      
    //  
    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));  
    //  
    fileOnlyName = "testDoc11_"+sb+".doc";  
      
    /** word */  
    String result = WordUtil.createWord2(dataMap, "testDoc11.ftl", filePath, fileOnlyName);  
      
    if(StringUtils.isNotBlank(result)){  
          
        downloadService.downLoad(inv, fileOnlyName, result);  
    }  
      
    return "@";  
}  
 

}


@ smilesnake first of all, thank you for sharing the code. It may be my problem. I did not describe the problem clearly. I am currently following your idea, but the problem is that the final doc document generated to the user is of xml type (you can see it when you save as) and when the user opens it and edits it and then saves it, it becomes a document with the suffix xml, which makes it impossible to open later. So my question is how to generate word type documents


this is a common problem of freemarker generating word documents, it is essentially a xml text, you can take a look at: http://www.xdocin.com/office., The result is the real docx format


is the landlord problem solved? I also encountered this problem.


landlord problem solved? I also encountered this problem


I also encountered this problem, is there any good solution?


has the problem of the landlord been solved? I also encountered this problem, ask God to teach me!

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3753a-4ecec.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3753a-4ecec.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?