Java 一段中的不同风格ApachePOI

Java 一段中的不同风格ApachePOI,java,apache-poi,Java,Apache Poi,XWPFParagraph bodyParagraph=docxModel.createParagraph(); bodypart.setalignment(段落Alignment.RIGHT);XWPFRun paragraphConfig=body段落.createRun(); paragraphConfig.setFontSize(25);paragraphConfig.setText(“您好 世界) 告诉我如何在一个段落中使用不同的样式,例如,您需要用粗体书写Hello,并强调世界?在W

XWPFParagraph bodyParagraph=docxModel.createParagraph(); bodypart.setalignment(段落Alignment.RIGHT);XWPFRun paragraphConfig=body段落.createRun(); paragraphConfig.setFontSize(25);paragraphConfig.setText(“您好 世界)


告诉我如何在一个段落中使用不同的样式,例如,您需要用粗体书写Hello,并强调世界?

Word
文档中,每个具有不同格式的文本都需要在自己的文本运行中。提供直接格式化文本的方法

因此,如果目标是一段包含

你好世界

然后,段落需要一个文本运行来显示Hello,然后一个文本运行来显示空格,一个文本运行来显示World

完整示例:

import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class CreateWordHelloWorld {

 public static void main(String[] args) throws Exception {
  XWPFDocument doc= new XWPFDocument();
  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run;

  //text run for "Hello" bold
  run = paragraph.createRun();
  run.setBold(true);
  run.setFontSize(25);
  run.setText("Hello");
  //text run for space 
  run = paragraph.createRun();
  run.setFontSize(25);
  run.setText(" ");
  //text run for "World" italic
  run = paragraph.createRun();
  run.setFontSize(25);
  run.setItalic(true);
  run.setText("World");

  FileOutputStream out = new FileOutputStream("WordDocument.docx");
  doc.write(out);
  out.close();
  doc.close();

 }
}

Word
文档中,具有不同格式的每个文本都需要在自己的文本运行中。提供直接格式化文本的方法

因此,如果目标是一段包含

你好世界

然后,段落需要一个文本运行来显示Hello,然后一个文本运行来显示空格,一个文本运行来显示World

完整示例:

import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class CreateWordHelloWorld {

 public static void main(String[] args) throws Exception {
  XWPFDocument doc= new XWPFDocument();
  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run;

  //text run for "Hello" bold
  run = paragraph.createRun();
  run.setBold(true);
  run.setFontSize(25);
  run.setText("Hello");
  //text run for space 
  run = paragraph.createRun();
  run.setFontSize(25);
  run.setText(" ");
  //text run for "World" italic
  run = paragraph.createRun();
  run.setFontSize(25);
  run.setItalic(true);
  run.setText("World");

  FileOutputStream out = new FileOutputStream("WordDocument.docx");
  doc.write(out);
  out.close();
  doc.close();

 }
}