使用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
相关推荐
代码不停10 分钟前
自动化测试(java)
java·开发语言·selenium·自动化
Smoothcloud润云39 分钟前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook1 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴1 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
诺伦2 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索
oooost2 小时前
pytorch学习笔记1
python·学习方法
鬼手点金2 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
数字融合2 小时前
透明化视频孪生虚实映射一体化融合技术
人工智能·python·数码相机
jack186893 小时前
Lovable.Dev 全栈应用快速落地实战指南
python
paopaokaka_luck3 小时前
滑雪场管理系统(AI智能助手流式对话,ECharts 运营数据分析、教练、雪具与场地一体化预约,钱包支付退款、订单核销与服务评价)
java·人工智能·spring boot·网络协议·数据分析·echarts