word文档java截取字符,使用Java:替换MS Word文件中的字符串

We need a Java library to replace strings in MS Word files.

Can anyone suggest?

解决方案

While there is MS Word support in Apache POI, it is not very good. Loading and then saving any file with other than the most basic formatting will likely garble the layout. You should try it out though, maybe it works for you.

There are a number of commercial libraries as well, but I don't know if any of them are any better.

The crappy "solution" I had to settle for when working on a similar requirement recently was using the DOCX format, opening the ZIP container, reading the document XML, and then replacing my markers with the right texts. This does work for replacing simple bits of text without paragraphs etc.

private static final String WORD_TEMPLATE_PATH = "word/word_template.docx";

private static final String DOCUMENT_XML = "word/document.xml";

/*....*/

final Resource templateFile = new ClassPathResource(WORD_TEMPLATE_PATH);

final ZipInputStream zipIn = new ZipInputStream(templateFile.getInputStream());

final ZipOutputStream zipOut = new ZipOutputStream(output);

ZipEntry inEntry;

while ((inEntry = zipIn.getNextEntry()) != null) {

final ZipEntry outEntry = new ZipEntry(inEntry.getName());

zipOut.putNextEntry(outEntry);

if (inEntry.getName().equals(DOCUMENT_XML)) {

final String contentIn = IOUtils.toString(zipIn, UTF_8);

final String outContent = this.processContent(new StringReader(contentIn));

IOUtils.write(outContent, zipOut, UTF_8);

} else {

IOUtils.copy(zipIn, zipOut);

}

zipOut.closeEntry();

}

zipIn.close();

zipOut.finish();

I'm not proud of it, but it works.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值