maven依赖
XML
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
测试类:
java
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import java.io.*;
public class WordMain {
public static void main(String[] args) throws IOException, InvalidFormatException {
// 创建一个XWPFDocument对象:
XWPFDocument document = new XWPFDocument();
// 添加段落(Paragraph)到文档中:
XWPFParagraph paragraph1 = document.createParagraph();
// 创建一个XWPFRun对象,并设置段落的文本内容、字体样式等
// 多个段落就创建多个XWPFParagraph
// 如果要在同一个段落中添加不同的文本格式,使用同一个XWPFParagraph,创建多个XWPFRun,分别对其进行样式设置即可
XWPFRun run1 = paragraph1.createRun();
run1.setText("hello word 文档");
run1.setFontSize(12);
run1.setBold(true);
// 可以设置其他样式,如字体、颜色等
// 创建一个CTColor对象,并设置颜色为红色(红色的RGB值为255, 0, 0)
CTColor color = CTColor.Factory.newInstance();
color.setVal("FF0000"); // 设置颜色为红色
// 创建一个CTR对象,并设置CTR的属性
CTR ctr = run1.getCTR();
CTRPr ctrPr = ctr.addNewRPr();
ctrPr.setColor(color);
// 添加表格(Table)到文档中:
int rows = 3;
int cols = 4;
XWPFTable table = document.createTable(rows, cols);
// 遍历表格单元格,并设置内容
for (int row = 0;
row < rows; row++) {
for (int col = 0; col < cols; col++) {
XWPFTableCell cell = table.getRow(row).getCell(col);
cell.setText("行 " + (row + 1) + " 列 " + (col + 1));
}
}
// 创建新的断落设置内容1.5间距
XWPFParagraph paragraph2 = document.createParagraph();
paragraph2.setSpacingBetween(1.5, LineSpacingRule.AUTO);
XWPFRun run2 = paragraph2.createRun();
run2.setText("hello word 内容");
// 插入图片
String imagePath = "D://image.png";
InputStream imageStream = new FileInputStream(imagePath);
XWPFParagraph paragraph3 = document.createParagraph();
XWPFRun run3 = paragraph3.createRun();
// 图片格式为JPEG
int format = XWPFDocument.PICTURE_TYPE_JPEG;
run3.addPicture(imageStream, format, "image", Units.toEMU(400), Units.toEMU(200));
// 将文档保存到文件
FileOutputStream out = new FileOutputStream("D://test1.docx");
document.write(out);
out.close();
// 将文档保存到输出流中(这个用于在前端点击导出时传入的HttpServletResponse)
// HttpServletResponse response = null;
// //获取输出流
// OutputStream outputStream = response.getOutputStream();
// //用文档写输出流
// document.write(outputStream);
// //刷新输出流
// outputStream.flush();
System.out.println("将文档保存成功!");
}
}
结果: