java使用poi操作word模板二----操作table

工作中遇到操作word中的table,添加新行填充数据;

基础maven依赖参考: java使用poi操作word模板一----普通读取和插入图片_apachepoi操作固定模版的word-优快云博客

工具类代码:

package com.example.demo.demos.web.file;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class WordTableTest {

    public static void main(String[] args) throws Exception {

        tableAddRowWithStyle();

//        tableAddRow();

//        doDocx();

//        fillTableDocumentWithValues();

//        fillDocumentWithValues();

    }

    private static void tableAddRowWithStyle() throws Exception {
        String wordUrl = "D:\\Backup\\Documents\\1卷宗目录.docx";
        String newWordUrl = "D:\\Backup\\Documents\\filled-document.docx";
        // 1. 加载现有的Word文档
        FileInputStream fis = new FileInputStream(wordUrl);
        XWPFDocument document = new XWPFDocument(fis);

        // 获取文档中的所有表格
        List<XWPFTable> tables = document.getTables();

        XWPFTable table = tables.get(0); // 获取第一个表格
        XWPFTableRow row = table.getRow(0);
        CTRow ctrow = CTRow.Factory.parse(row.getCtRow().newInputStream());//重点行
        XWPFTableRow newRow = new XWPFTableRow(ctrow, table);
        List<XWPFTableCell> tableCells = newRow.getTableCells();
        int i = 1;
        for (XWPFTableCell tableCell : tableCells) {
            //设置文本
            tableCell.setText(String.valueOf(i));
        }
        table.addRow(newRow, i);

        // 5. 将修改后的文档保存到新的文件
        FileOutputStream out = new FileOutputStream(newWordUrl);
        document.write(out);

        // 6. 关闭所有打开的资源
        out.close();
        fis.close();
        document.close();
    }

    private static void tableAddRow() throws Exception {
        String wordUrl = "D:\\Backup\\Documents\\1卷宗目录.docx";
        String newWordUrl = "D:\\Backup\\Documents\\filled-document.docx";
        // 1. 加载现有的Word文档
        FileInputStream fis = new FileInputStream(wordUrl);
        XWPFDocument document = new XWPFDocument(fis);

        // 获取文档中的所有表格
        List<XWPFTable> tables = document.getTables();

        XWPFTable table = tables.get(0); // 获取第一个表格
        XWPFTableRow newRow = table.createRow(); // 添加新行
        List<XWPFTableCell> tableCells = newRow.getTableCells();
        int i = 1;
        for (XWPFTableCell tableCell : tableCells) {
            //设置文本
            tableCell.setText(String.valueOf(i));
        }

        // 5. 将修改后的文档保存到新的文件
        FileOutputStream out = new FileOutputStream(newWordUrl);
        document.write(out);

        // 6. 关闭所有打开的资源
        out.close();
        fis.close();
        document.close();
    }

    private static void fillDocumentWithValues() throws Exception {
        String wordUrl = "D:\\Backup\\Documents\\1卷宗目录.docx";
        String newWordUrl = "D:\\Backup\\Documents\\filled-document.docx";
        // 1. 加载现有的Word文档
        FileInputStream fis = new FileInputStream(wordUrl);
        XWPFDocument document = new XWPFDocument(fis);

        // 2. 遍历文档中的所有段落
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        System.out.println("paragraphs.size() = " + paragraphs.size());
        for (XWPFParagraph paragraph : paragraphs) {
            // 3. 遍历每个段落中的所有run
            List<XWPFRun> runs = paragraph.getRuns();
            if (runs != null) {
                for (XWPFRun run : runs) {
                    // 4. 获取文本并替换占位符
                    String text = run.getText(0);
                    if (text != null) {
                        text = text.replaceAll("\\{\\{name\\}\\}", "John Doe");
                        text = text.replaceAll("\\{\\{age\\}\\}", "30");
                        run.setText(text, 0);
                    }
                }
            }
        }
        // 5. 将修改后的文档保存到新的文件
        FileOutputStream out = new FileOutputStream(newWordUrl);
        document.write(out);

        // 6. 关闭所有打开的资源
        out.close();
        fis.close();
        document.close();
    }

    private static void fillTableDocumentWithValues() throws Exception {
        String wordUrl = "D:\\Backup\\Documents\\1卷宗目录.docx";
        String newWordUrl = "D:\\Backup\\Documents\\filled-document.docx";
        // 1. 加载现有的Word文档
        FileInputStream fis = new FileInputStream(wordUrl);
        XWPFDocument document = new XWPFDocument(fis);

        // 获取文档中的所有表格
        List<XWPFTable> tables = document.getTables();

        for (XWPFTable table : tables) {
            // 遍历表格中的每一行
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                XWPFTableRow row = table.getRow(i);

                // 遍历行中的每一列
                for (int j = 0; j < row.getTableCells().size(); j++) {
                    XWPFTableCell cell = row.getCell(j);
                    //取得单元格的内容
                    String text = cell.getText();
                    System.out.println("text = " + text);
                    if (text != null) {
                        text = text.replaceAll("\\{\\{name\\}\\}", "John Doe");
                        text = text.replaceAll("\\{\\{age\\}\\}", "30");
                        cell.setText(text);
                    }
                }
            }
        }

        // 5. 将修改后的文档保存到新的文件
        FileOutputStream out = new FileOutputStream(newWordUrl);
        document.write(out);

        // 6. 关闭所有打开的资源
        out.close();
        fis.close();
        document.close();
    }

    // 读取doc文档中表格数据示例
    public static List<String> doDocx() throws Exception {
        String wordUrl = "D:\\Backup\\Documents\\1卷宗目录.docx";
        String newWordUrl = "D:\\Backup\\Documents\\filled-document.docx";
        //用于存放预览信息
        List<String> list = new ArrayList<String>();
        //获取文件流
        InputStream is = new FileInputStream(wordUrl);
        //获取文件对象
        XWPFDocument doc = new XWPFDocument(is);
        //获取所有的表格对象
        List tables =doc.getTables();
        //因我文档中只有一个所以这里没有去遍历,直接获取指定表格对象
        XWPFTable table = (XWPFTable) tables.get(0);
        //迭代行,默认从0开始
        for (int j = 0; j < table.getRows().size(); j++) {
            //当前行
            XWPFTableRow tr = table.getRow(j);
            //用于存放一行数据,不需要可以不用
            String rowText = "";
            //迭代列,默认从0开始
            for (int x = 0; x < tr.getTableCells().size(); x++) {
                //取得单元格
                XWPFTableCell td = tr.getCell(x);
                //取得单元格的内容
                String text = td.getText();
                System.out.println("text = " + text);
                //自己用“ ”区分两列数据,根据自己需求 可以省略
                if (StringUtils.isEmpty(rowText)){
                    rowText = text;
                }else {
                    rowText = rowText + " " + text;
                }
            }
            System.out.println("rowText = " + rowText);
            list.add(rowText);
        }

        return list;
    }


}

效果:

如果需要从jar包的resource中读取文件:

文件位置:

代码:

import org.springframework.core.io.ClassPathResource;


ClassPathResource classPathResource = new ClassPathResource("static/测试卷宗目录.docx");
        InputStream fis = classPathResource.getInputStream();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值