问题描述
我的Word模板很少,我的要求是使用Java根据用户输入替换文档中的一些单词/占位符。我尝试了很多库,包括2-3个版本的 docx4j
,但没有什么工作,他们都没有做任何事情!
I do have few Word templates, and my requirement is to replace some of the words/place holders in the document based on the user input, using Java. I tried lot of libraries including 2-3 versions of docx4j
but nothing work well, they all just didn't do anything!
我之前已经问过这个问题,但我尝试了所有我知道的选项。那么,使用什么java库我可以真正替换/编辑这些模板?我的偏好是易于使用/几行代码类型库。
I know this question has been asked before, but I tried all options I know. So, using what java library I can "really" replace/edit these templates? My preference goes to the "easy to use / Few line of codes" type libraries.
我使用的是Java 8,我的MS Word模板在MS Word 2007中。
I am using Java 8 and my MS Word templates are in MS Word 2007.
更新
此代码是使用SO成员提供的代码示例编写的 Joop Eggen
This code is written by using the code sample provided by SO member 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)
推荐答案
尝试。 POI
可以使用 doc
和 docx
,但 docx
更有据可查,因此更好地支持它。
Try Apache POI. POI
can work with doc
and docx
, but docx
is more documented therefore support of it better.
UPD :您可以使用,它使用POI。此外,我建议使用 xlsx
作为模板,因为它更适合
UPD: You can use XDocReport, which use POI. Also I recomend to use xlsx
for templates because it more suitable and more documented
这篇关于如何使用Java编辑MS Word文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!