有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ApachePOI如何使用java删除包含字符串的word表的行

此代码删除表中的所有行,但我想删除特定行(如果行包含例如数字2)

import java.io.FileOutputStream;
import java.io.FileInputStream;

import java.util.List;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;


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

    FileInputStream fis = new FileInputStream("C:\\TMPL.docx");


    XWPFDocument doc = new XWPFDocument(fis);

    List<XWPFTable> tables = doc.getTables();
    XWPFTable table = tables.get(0);

    XWPFTableRow[] rows = table.getRows().toArray(new XWPFTableRow[0]);

    for (int r = 0; r < rows.length; r++) {
        if (r > 0) {
            XWPFTableRow row = rows[r];
            CTTc[] cells = row.getCtRow().getTcList().toArray(new CTTc[0]);
            for (int c = 0; c < cells.length; c++) {
                CTTc cTTc = cells[c];

                //clear only the paragraphs in the cell, keep cell styles
                cTTc.setPArray(new CTP[] {CTP.Factory.newInstance()});
                cells[c] = cTTc;
            }
            row.getCtRow().setTcArray(cells);
            //System.out.println(row.getCtRow());
        }
    }

    doc.write(new FileOutputStream("new document.docx"));
}

   

共 (1) 个答案

  1. # 1 楼答案

    找到包含数字2的行后,可以使用方法table.removeRow(i)(有文档记录的here)删除位置i处的完整行