How does java convert an xml-type word document into a word-type document

  java, question

My demand is this:
Word document type is xml, open it with a text editor and see the following code (I only copied the head part of the code)
How can java convert it into doc document of word type? Apache poi seems to only convert word document 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 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: PartPKG: Name = "/_ RELS/.RELS" PKG: Content-Type = "Application/VND. Open xml Formats-Package. Relationships Plus 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 use office2003 or 2007 to edit the style of word, then save it as xml, translate xml into FreeMarker template, and finally use java to parse FreeMarker template and output Doc. After testing, the word document generated in this way completely conforms to the office standard, the style and content control are very convenient, printing will not deform, and the generated document is exactly the same as the edited document in office.
Use xml as export scheme.

First create a word document, fill in a template in word according to requirements, then replace the corresponding data with variable $ {}, then save the document in xml document format, use document editor to open the xml document, remove redundant xml symbols, use Freemarker to read the document, then replace the variable, and output the word document

Freemarker jar package required

/**

  • Project Name:exam-services
  • File Name:DownloadService.java
  • Package Name:com.wt.service.download
  • Date: September 28, 2016, 4:44:37 p.m.
  • 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/>
  • Function: file download. < br/ >
  • Reason: ADD REASON. <br/>
  • Date: September 28, 2016, 4: 44: 37 p.m. < 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 be downloaded
 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 into 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= "plus 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);
 bracket
 bouts.flush();  //The flush () method must be called here
 
 } catch (Exception e) {
 
 e.printStackTrace();
 } finally {
 if (bouts !  = null) {
 
 bouts.close();
 bracket
 if (outs !  = null) {
 
 outs.close();
 bracket
 if (bins !  = null) {
 
 bins.close();
 bracket
 if (ins !  = null) {
 
 ins.close();
 bracket
 bracket
 } else {
 Info ("exported file does not exist");
 bracket
 bracket

bracket

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 p.m.

*/
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 under com.lun.template package.
 configuration.setClassForTemplateLoading(WordUtil.class, "\\com\\wt\\common\\util\\");
 
 //Get Template
 Template template = configuration.getTemplate(templateName);
 
 //Output File
 Fileoutpile = newfile (filepath plus File.separator plus fileName);
 
 //If the output destination folder does not exist, create
 if (!  outFile.getParentFile().exists()) {
 outFile.getParentFile().mkdirs();
 bracket
 
 //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 stream
 out.flush();
 out.close();
 
 Return filePath plus File.separator plus fileName;
 } catch (Exception e) {
 e.printStackTrace();
 bracket
 
 return null;
 bracket

bracket

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 p.m.

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

@Autowired
 private DownloadService downloadService;
 
 private String filePath;  //file path

// private String fileName; //File Name

private String fileOnlyName;  //Unique name of file
 
 
 
 /**
 * createWord2: (Here, use one sentence to describe the function of this method). < 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 {
 
 /* * Data Required for Assembling word Pages */
 Map<String, Object> dataMap = new HashMap<String, Object>();
 
 Simpleddateformat sdf = newsimpleddateformat ("yyyy MM dd");
 
 dataMap.put("startTime", sdf.format(new Date()));
 dataMap.put("endTime", sdf.format(new Date()));
 dataMap.put("count", 1);
 dataMap.put("username", "Tom");
 Put ("courcename", "physics");
 Put ("classname", "class 1");
 DataMap.put("materialName ","sports ");
 dataMap.put("materialVer", 1.0);
 DataMap.put("teachAim ","nuckle 12421 price can be proud of space avatar garbage collection, file attachment security parity, funkel 12421 price can be proud of space avatar garbage collection, file attachment security parity, funkel 12421 price can be proud of space avatar garbage collection, file attachment security parity, funkel 12421 price can be proud of space avatar garbage collection, file attachment security parity, funkel 12421 price can be proud of space avatar garbage collection, file attachment security parity, funkel 12421 price can be proud of space avatar garbage collection, file attachment security parity, funkel 12421 price ")
 
 //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));
 //Unique name of file
 FileOnlyName = "testDoc11_ "plus sb plus". doc ";
 
 /* * generate word */
 String result = WordUtil.createWord2(dataMap, "testDoc11.ftl", filePath, fileOnlyName);
 
 if(StringUtils.isNotBlank(result)){
 
 downloadService.downLoad(inv, fileOnlyName, result);
 bracket
 
 return "@";
 bracket

bracket