简体   繁体   English

如何将 Apache POI 中的段落部分加粗? (Word 文档)

[英]How to partially bold a Paragraph in Apache POI? (Word Documents)

I been working with Apache POI recently and i can't figure out how to set a string like this: "Hello World ".我最近一直在使用 Apache POI,但我不知道如何设置这样的字符串:“Hello World ”。 This is what i been trying这就是我一直在尝试的

    XWPFDocument document = new XWPFDocument();
    String path = System.getProperty("user.home")+ "/Desktop/"+ array.get(0); //"array" is an ArrayList<String>
    path = path.replace("\\","/");
            
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();
    String str1 = "Price: ";
    String str2 = array.get(1); // This needs to be Bold
    run.setFontSize(9);
    run.setFontFamily("Arial");
    run.setText(str1);
    run.setBold(true);
    run.setText(str2);
    paragraph.setSpacingBetween(1);
    paragraph.setAlignment(ParagraphAlignment.RIGHT);
    try {
        FileOutputStream output = new FileOutputStream(ruta);
        document.write(output);
        output.close();
        document.close();
    }catch(Exception e) {
        e.printStackTrace();
    }

I know that "run.setBold(true)" its supposed to apply it to the whole parapraph but its the only thing i found for word documents so i need some help to fix this.我知道“run.setBold(true)”它应该将它应用于整个段落,但它是我为 word 文档找到的唯一东西,所以我需要一些帮助来解决这个问题。 Thanks for your help.谢谢你的帮助。

In general, a run is a run, and a paragraph is a paragraph.一般来说,一个运行就是运行,一个段落就是一个段落。 Different things.不同的东西。 You can make the run a single word, adjacent words or an entire paragraph.您可以使运行单个单词、相邻单词或整个段落。 The only thing that matters is a) if you want to "bold" something, then b) you need to "bold" the corresponding run.唯一重要的是a)如果你想“加粗”某些东西,那么b)你需要“加粗”相应的运行。

Confusing things, in POI you create a "run" in terms of a "paragraph":(令人困惑的是,在 POI 中,您根据“段落”创建“运行”:(

... BUT... ... 但...

You can have multiple runs - with different attributes - in the SAME paragraph.您可以在同一段落中进行多次运行 - 具有不同的属性。

For example:例如:

  XWPFParagraph p = doc.createParagraph();
  XWPFRun r1 = p.createRun();
  r1.setText("Some Text");
  r1.setBold(true);
  r2 = p.createRun();
  r2.setText("Goodbye");

I haven't tried this code, but I believe "Some Text" will be bold, and "Goodbye" won't.我没有尝试过这段代码,但我相信“Some Text”会加粗,而“Goodbye”不会。 You can also experiment with different syntax, to see what works best for you.您还可以尝试不同的语法,看看哪种最适合您。

I hope that helps - and good luck!我希望这会有所帮助——祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM