Converting a file with “.dotx” extension (template

2019-03-06 20:33发布

问题:

How to convert a ".dotx" Word template to a plain ".docx" using a POI APIs or Docx4j?

回答1:

The need is changing the content type of /word/document.xml from application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml to application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml.

Example using apache poi 4.0.1:

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

public class WordReadDOTXSaveDOCX {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument(new FileInputStream("StudentReport.dotx"));
  document.getPackage().replaceContentType(
   "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
   "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");

  FileOutputStream out = new FileOutputStream("TheDocumentFromDOTXTemplate.docx");
  document.write(out);
  out.close();
  document.close();
 }
}