首页 > 解决方案 > 如何使用java删除包含字符串的单词表的行

问题描述

此代码删除表的所有行,但我想删除特定行(如果行包含例如数字 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"));
}

   

标签: javaapache-poi

解决方案


找到包含数字 2 的行后,您可以使用该方法table.removeRow(i)在此处记录)删除 position 处的完整行i


推荐阅读