将扩展名为“ .dotx”的文件(模板)转换为“ docx”(Word文件)

时间:2019-01-26 09:34:44

标签: java apache-poi docx docx4j

如何使用POI API或Docx4j将“ .dotx” Word模板转换为普通的“ .docx”?

1 个答案:

答案 0 :(得分:3)

需要将/word/document.xml的内容类型从application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml更改为application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml

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