引入poi依赖包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
创建XWPFDocument对象
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Hello Word");
XWPFParagraph段落属性
paragraph.setAlignment(ParagraphAlignment.RIGHT);
paragraph.setFontAlignment(2);
paragraph.setVerticalAlignment(TextAlignment.BOTTOM);
paragraph.setWordWrapped(true);
paragraph.setNumID(BigInteger.valueOf(1));
paragraph.setPageBreak(true);
paragraph.setBorderTop(Borders.DOT_DASH);
paragraph.setBorderBottom(Borders.DOT_DASH);
paragraph.setBorderLeft(Borders.DOT_DASH);
paragraph.setBorderRight(Borders.DOT_DASH);
paragraph.setBorderBetween(Borders.SINGLE);
paragraph.setFirstLineIndent(400);
paragraph.setIndentationFirstLine(400);
paragraph.setIndentationHanging(400);
paragraph.setIndentationLeft(400);
paragraph.setIndentationRight(400);
paragraph.setIndentFromLeft(400);
paragraph.setIndentFromRight(400);
paragraph.setSpacingAfter(200);
paragraph.setSpacingAfterLines(400);
paragraph.setSpacingBefore(200);
paragraph.setSpacingBeforeLines(200);
paragraph.setSpacingBetween(3.1,LineSpacingRule.AT_LEAST);
paragraph.setSpacingLineRule(LineSpacingRule.AUTO);
XWPFRun属性
run.setText("测试文本");
run.setFontSize(30);
run.setFontFamily("仿宋", XWPFRun.FontCharRange.cs);
run.setBold(true);
run.setTextScale(80);设置文本比例(80%)
run.setCharacterSpacing(100);
run.setTextPosition(200);
run.setKerning(200);
run.setColor("FF0000");
run.setItalic(true);
run.setStrikeThrough(true);
run.setDoubleStrikethrough(true);
run.setSubscript(VerticalAlign.BASELINE);
run.setShadow(true);
run.setEmbossed(true);
run.setImprinted(true);
run.setSmallCaps(true);
run.setCapitalized(true);
run.setVanish(true);
run.setVerticalAlignment("baseline");
run.setEmphasisMark("circle");
run.setUnderline(UnderlinePatterns.THICK);
run.setUnderlineColor("FFFFFF");
run.setUnderlineThemeColor("FFFFFC");
run.setTextHighlightColor("FF0000");
run.addBreak();
run.addCarriageReturn();
run.addTab();
本地测试代码
public static void main(String[] args) {
FileOutputStream fos = null;
String fileName = UUIDUtil.randomUUID8();
try {
fos = new FileOutputStream("E:/test/" + fileName + ".docx");
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Hello Word");
document.write(fos);
Desktop.getDesktop().open(new File("E:/test/" + fileName + ".docx"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}