英文:
How to remove rows of a word table that contains a string using java
问题
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"));
}
英文:
this code remove all the rows of the table, but i want to remove a specific rows(if rows contain for example number 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
得分: 2
一旦您找到包含数字2的行,您可以使用方法table.removeRow(i)
(文档链接见此处)来删除位置为i
的整行。
英文:
Once you find a row containing the number 2, you can use the method table.removeRow(i)
(documented here) to remove the complete row at position i
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论