【发布时间】:2014-11-18 21:21:57
【问题描述】:
我确实有几个 Word 模板,我的要求是使用 Java 根据用户输入替换文档中的一些单词/占位符。我尝试了很多库,包括 docx4j 的 2-3 个版本,但没有任何效果,它们都没有做任何事情!
我知道以前有人问过这个问题,但我尝试了所有我知道的选项。那么,使用什么 java 库我可以“真正”替换/编辑这些模板?我更喜欢“易于使用/几行代码”的类型库。
我使用的是 Java 8,我的 MS Word 模板在 MS Word 2007 中。
更新
此代码是使用SO成员Joop Eggen提供的代码示例编写的
public Main() throws URISyntaxException, IOException, ParserConfigurationException, SAXException
{
URI docxUri = new URI("C:/Users/Yohan/Desktop/yohan.docx");
Map<String, String> zipProperties = new HashMap<>();
zipProperties.put("encoding", "UTF-8");
FileSystem zipFS = FileSystems.newFileSystem(docxUri, zipProperties);
Path documentXmlPath = zipFS.getPath("/word/document.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(Files.newInputStream(documentXmlPath));
byte[] content = Files.readAllBytes(documentXmlPath);
String xml = new String(content, StandardCharsets.UTF_8);
//xml = xml.replace("#DATE#", "2014-09-24");
xml = xml.replace("#NAME#", StringEscapeUtils.escapeXml("Sniper"));
content = xml.getBytes(StandardCharsets.UTF_8);
Files.write(documentXmlPath, content);
}
但是这会返回以下错误
java.nio.file.ProviderNotFoundException: Provider "C" Not found
at: java.nio.file.FileSystems.newFileSystem(FileSystems.java:341) at java.nio.file.FileSystems.newFileSystem(FileSystems.java:341)
at java.nio.fileFileSystems.newFileSystem(FileSystems.java:276)
【问题讨论】:
-
也许可以考虑(我会选择 Apache HWPF):*.com/questions/203174/…
-
@CsBalazsHungary:链接创建于 5 年前。那时还没有 Java 8。
-
MS Word 2007 已经是 .docx 了吗?因为该格式是完美的,您可以使用 java zip 文件系统,并更改 /word/content.xml。这些库不保证原始格式。
-
@Sniper 遗憾的是它确实会导致问题:(
-
@JoopEggen:是的,它是 Docx。更喜欢看图书馆,你知道,很简单。