使用Apache POI(Java)创建docx文档和表格

1、引入poi 依赖组件

c 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

2、使用

1.引入库

c 复制代码
import org.apache.poi.xwpf.usermodel.*;

2.初始化一个空文件,生成文档后写入文件中

c 复制代码
public static File createFile() {
    Filefile = null;
    try {
        // 初始化模板文件
        String path = "./testFile.docx";
        Path path2 = Paths.get(path);
        boolean exists = Files.exists(path2);
        if (exists) {
            Files.delete(path2);
            file = new File(path);
        } else {
            file = new File(path);
        }
    } catch (IOException e) {
        log.error("初始化file失败", e.getMessage());
    }
    return file;
}

3.创建 XWPFDocument 对象,create段落

c 复制代码
XWPFDocument document = new XWPFDocument();
// 创建文档中的段落
XWPFParagraph paragraph = document.createParagraph();
paragraph .setAlignment(ParagraphAlignment.CENTER); // 对齐方式
XWPFRun run = paragraph .createRun();
// 设置段落属性
run.setText("这是一段文字,代表一个段落内容!");
run.setBold(true);
run.setFontSize(18);
run.setFontFamily("微软雅黑");
run.addCarriageReturn();// 增加回车空行
run.setKerning(30);
段落循环创建

4.使用 XWPFDocument 对象创建表格

c 复制代码
// 创建表格 n行*m列(创建table 时,会有一个默认一行一列的表格)
XWPFTable table = document.createTable(n, m);
table.setWidth("100%");// 表格所占文档宽度
// 获取第一行
XWPFTableRow row = table.getRow(0);// 设置表格标题行
// 标题行,每一列的名称都放入List中,可以循环设置列标题
List<String> titles = Lists.newArrayList();// 标题行集合
for (int i = 0; i < titles.size(); i++) {
	XWPFTableCell cell0 = row.getCell(i);
	cell0.setWidth(width + "%"); // 设置单元格宽度
	cell0.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置对齐方式

	// 单元格的标题假设为一个段落内容,就可以方便设置标题的样式,字体、大小、颜色等
	XWPFParagraph paragraph = cell0.addParagraph();
    paragraph.setAlignment(ParagraphAlignment.CENTER);// 设置对齐方式
    XWPFRun run = paragraph.createRun();
    run.setText("这是一个标题");
    run.setFontSize(16);// 大小
    run.setBold(true);// 是否加粗
    run.setFontFamily("方正仿宋");// 字体格式
}
* 或使用简单方式创建标题行,使用自适应样式
c 复制代码
XWPFTableCell cell = rows.getCell(0);
buildAlignment(cell); // 单元格中的标题内容对齐方式
cell.setWidth("5%"); // 宽度
cell.setText("这也是一个标题");

/**
* 设置单元格样式
* @param cell cell
*/
private static void buildAlignment(XWPFTableCell cell) {
  CTTcPr cellPr = cell.getCTTc().getTcPr() == null ? cell.getCTTc().addNewTcPr() : cell.getCTTc().getTcPr();
  if (cellPr.getVAlign() == null) {
      cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
  } else {
      cellPr.getVAlign().setVal(STVerticalJc.CENTER);
  }
  XWPFParagraph paragraph1=cell.getParagraphArray(0);
  paragraph1.setAlignment(ParagraphAlignment.CENTER);
}

5.将创建的XWPFDocument对象 写入文件中

c 复制代码
FileOutputStream fos= new FileOutputStream(file);
document.write(fos);
fos.close(); // 关闭流增加判断,不可直接关闭
// docx文件创建结束!

up
相关推荐
多米Domi01125 分钟前
0x3f 第49天 面向实习的八股背诵第六天 过了一遍JVM的知识点,看了相关视频讲解JVM内存,垃圾清理,买了plus,稍微看了点确定一下方向
jvm·数据结构·python·算法·leetcode
饺子大魔王的男人25 分钟前
Remote JVM Debug+cpolar 让 Java 远程调试超丝滑
java·开发语言·jvm
人工智能训练6 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
yaoming1686 小时前
python性能优化方案研究
python·性能优化
码云数智-大飞7 小时前
使用 Python 高效提取 PDF 中的表格数据并导出为 TXT 或 Excel
python
Hx_Ma168 小时前
SpringMVC框架提供的转发和重定向
java·开发语言·servlet
biuyyyxxx8 小时前
Python自动化办公学习笔记(一) 工具安装&教程
笔记·python·学习·自动化
期待のcode8 小时前
原子操作类LongAdder
java·开发语言
极客数模8 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
舟舟亢亢9 小时前
Java集合笔记总结
java·笔记