[POI]Word文档的相关操作

本文介绍了如何使用Apache POI 3.9库在Java中进行Word文档操作,包括创建新的Word文档并插入表格,以及在已有的Word文档上追加表格。还提供了带有书签的test.docx文件作为示例,展示了最终的生成效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是本文中需要用到的JAR包(POI3.9)
POI3.9

创建一个Word文档,并且创建表格

    String outputFile = "d:\\text\\test1.docx";
    // New Document
    XWPFDocument document = new XWPFDocument();
    // New Table,生成一个一行一列的表格
    XWPFTable tableOne = document.createTable();


    //获取Table的第一行
    XWPFTableRow tableOneRowOne = tableOne.getRow(0);
    //给Table的第一行第一列单元格赋值
    tableOneRowOne.getCell(0).setText("第1行第1列");
    //新建第2列并赋值
    tableOneRowOne.createCell().setText("第1行第2列");
    tableOneRowOne.createCell().setText("第1行第3列");

    //新建一行
    XWPFTableRow tableOneRowTwo = tableOne.createRow();
    tableOneRowTwo.getCell(0).setText("第2行第1列");
    tableOneRowTwo.getCell(1).setText("第2行第2列");
    tableOneRowTwo.getCell(2).setText("第2行第3列");

    //新建一行
    XWPFTableRow tableOneRowThree = tableOne.createRow();
    tableOneRowThree.getCell(0).setText("第3行第1列");
    tableOneRowThree.getCell(1).setText("第3行第2列");
    tableOneRowThree.getCell(2).setText("第3行第3列");

    FileOutputStream fOut;
    try {
        fOut = new FileOutputStream(outputFile);
        document.write(fOut); 
        fOut.flush();
        // 操作结束,关闭文件
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

在已有Word文档的基础上继续创建表格

test.docx(表格中带有书签)
word

    String inputFile = "d:\\text\\test.docx";
    String outputFile = "d:\\text\\test1.docx";
    // New Document
    XWPFDocument document = new XWPFDocument(new FileInputStream(inputFile));
    // 获取第一个Table
    XWPFTable tableOne = document.getTables().get(0);

    //获取Table的第一行
    XWPFTableRow tableOneRowOne = tableOne.getRow(0);
    tableOneRowOne.getCell(0).setText("第1行第1列");
    tableOneRowOne.getCell(1).setText("第1行第2列");

    //新建一行
    XWPFTableRow tableOneRowTwo = tableOne.createRow();
    tableOneRowTwo.getCell(0).setText("第2行第1列");
    tableOneRowTwo.getCell(1).setText("第2行第2列");

    //新建一行
    XWPFTableRow tableOneRowThree = tableOne.createRow();
    tableOneRowThree.getCell(0).setText("第3行第1列");
    tableOneRowThree.getCell(1).setText("第3行第2列");

    FileOutputStream fOut;
    try {
        fOut = new FileOutputStream(outputFile);
        document.write(fOut); 
        fOut.flush();
        // 操作结束,关闭文件
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

最后的生成效果演示

word1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值