gpt4 book ai didi

java - Apache POI 字 : find text and change font

转载 作者:行者123 更新时间:2023-11-30 08:37:15 25 4
gpt4 key购买 nike

我想在 XWPFDocument 中找到某些文本的所有出现并设置其字体。无法理解如何根据 Scanner 或类似的东西获取选择(Run 对象?)。

    XWPFDocument doc = new XWPFDocument();
try (FileOutputStream fos = new FileOutputStream(new File("c:\\temp\\document1.docx"))){
XWPFParagraph par = doc.createParagraph();
XWPFRun run = par.createRun();
run.setText("Абзац создан командой doc.createParagraph()");
par = doc.createParagraph();
run = par.createRun();
run.setText("Чтобы хорошо читалось, на doc.createParagraph() наложен стиль");
XWPFWordExtractor we = new XWPFWordExtractor(doc);
Scanner scanner = new Scanner(we.getText());
Pattern words = Pattern.compile("doc.createParagraph()");
while (scanner.hasNextLine()) {
String key = scanner.findInLine(words);
run.getTextPosition();
while (key != null) {
scanner.next();
key = scanner.findInLine(words);
}
scanner.nextLine();
}
doc.write(fos);
} catch (Exception e) {
e.printStackTrace();
}

在@AlexisDelahaye 回答后编辑。当前的解决方法是删除现有的运行并创建新的:

    XWPFDocument doc = new XWPFDocument();
try (FileOutputStream fos = new FileOutputStream(new File("c:\\temp\\document1.docx"))){
// Простой абзац с текстом
String specText = "doc.createParagraph\\(\\)";
XWPFParagraph par = doc.createParagraph();
XWPFRun run = par.createRun();
run.setText("Абзац создан командой doc.createParagraph()");
par = doc.createParagraph();
run = par.createRun();
run.setText("Чтобы хорошо читалось, на doc.createParagraph() наложен стиль");
// Смена шрифта для вхождения текста в каждый абзац
for (XWPFParagraph curPar : doc.getParagraphs()) {
String parText = curPar.getText();
boolean endWithSpec = parText.endsWith(specText.replace("\\", ""));
curPar.removeRun(0);
for (String curPart : parText.split(specText)) {
XWPFRun r = curPar.createRun();
r.setText(curPart);
r.setFontSize(10);
r = curPar.createRun();
r.setText(specText.replace("\\", ""));
r.setFontSize(20);
}
if (!endWithSpec) {
curPar.removeRun(curPar.getRuns().size() - 1);
}
}

最佳答案

找到这个 POI-XWPF quick guide . 你是对的,你需要使用 Run 对象

Specific Text Extraction

To get specific bits of text, first create a org.apache.poi.xwpf.XWPFDocument.

Select the IBodyElement of interest (Table, Paragraph etc), and from there get a XWPFRun.

Finally fetch the text and properties from that.

所以你的代码可能是这样的

List<XWPFRun> runs = par.getRuns();
for(int i = 0 ; i < runs.size() - 1 ; i++) {
XWPFRun run = runs.get(i);
int index=0;
// a run contains many text so you want to parse them as well :
String text = run.getText(index);
while(text !=null ){
if(text.contains("occurencyYourLookingFor")) {
run.setFontFamily("Arial");
}
text = run.getText(++index);
}
}

关于java - Apache POI 字 : find text and change font,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37342488/

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