gpt4 book ai didi

header - 如何使用 poi 3.8 替换 java 中 docx 标题中的占位符

转载 作者:行者123 更新时间:2023-12-02 11:45:26 24 4
gpt4 key购买 nike

我正在尝试替换 docx 文件标题中的标记。我已经处理了段落和表格中的标记替换,但它没有选择标题数据。我使用 apache poi 3.8 并使用 eclipse ID 在 java 中进行编码。谢谢

最佳答案

此方法将替换整个文档中表格、标题和段落中的所有选定文本。

public XWPFDocument replacePOI(XWPFDocument doc, String placeHolder, String replaceText){
// REPLACE ALL HEADERS
for (XWPFHeader header : doc.getHeaderList())
replaceAllBodyElements(header.getBodyElements(), placeHolder, replaceText);
// REPLACE BODY
replaceAllBodyElements(doc.getBodyElements(), placeHolder, replaceText);
return doc;
}

private void replaceAllBodyElements(List<IBodyElement> bodyElements, String placeHolder, String replaceText){
for (IBodyElement bodyElement : bodyElements) {
if (bodyElement.getElementType().compareTo(BodyElementType.PARAGRAPH) == 0)
replaceParagraph((XWPFParagraph) bodyElement, placeHolder, replaceText);
if (bodyElement.getElementType().compareTo(BodyElementType.TABLE) == 0)
replaceTable((XWPFTable) bodyElement, placeHolder, replaceText);
}
}

private void replaceTable(XWPFTable table, String placeHolder, String replaceText) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (IBodyElement bodyElement : cell.getBodyElements()) {
if (bodyElement.getElementType().compareTo(BodyElementType.PARAGRAPH) == 0) {
replaceParagraph((XWPFParagraph) bodyElement, placeHolder, replaceText);
}
if (bodyElement.getElementType().compareTo(BodyElementType.TABLE) == 0) {
replaceTable((XWPFTable) bodyElement, placeHolder, replaceText);
}
}
}
}
}

private void replaceParagraph(XWPFParagraph paragraph, String placeHolder, String replaceText) {
for (XWPFRun r : paragraph.getRuns()) {
String text = r.getText(r.getTextPosition());
if (text != null && text.contains(placeHolder)) {
text = text.replace(placeHolder, replaceText);
r.setText(text, 0);
}
}
}

关于header - 如何使用 poi 3.8 替换 java 中 docx 标题中的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com