Ваше требования «чтобы удалить весь текст из строк 2 и до конца» будет немного сложно выполнить так как 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.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
/*
needs the full ooxml-schemas-1.3.jar as mentioned in https://poi.apache.org/faq.html#faq-N10025
since the CTRowImpl is not fully shipped with poi-ooxml-schemas-3.13-*.jar
*/
public class WordCleanTableRows {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("document.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"));
}
}
Это нуждается в полной OOXML-SCHEMAS-1.3.jar, как указано в https://poi.apache.org/faq.html#faq-N10025 поскольку CTRowImpl не полностью поставляется с пои-OOXML-схем-3.13 -. * Баночку.
Без полной версии ooxml-schemas-1.3.jar вы можете просто удалить все строки, кроме первой, и добавить новые.
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.List;
import org.apache.poi.xwpf.usermodel.*;
public class WordCleanTableRows2 {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("document.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];
table.removeRow(1); //remove second row. others shift upwards
table.createRow(); //add new row at the end
}
}
doc.write(new FileOutputStream("new document.docx"));
}
}
Edit:
Следующая должна работать без OOXML-схем-1.3.jar и сделать то же самое, как мой первый пример.
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.STOnOff;
import java.math.BigInteger;
public class WordCleanTableRows3 {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("document.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];
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
//get CTTc and replace the CTPArray with one empty CTP
cell.getCTTc().setPArray(new CTP[] {CTP.Factory.newInstance()});
//set some default styles for the paragraphs in the cells:
//http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/wordprocessingml/x2006/main/CTParaRPr.java
CTP cTP = cell.getCTTc().getPArray(0);
cTP.addNewPPr();
cTP.getPPr().addNewRPr();
cTP.getPPr().getRPr().addNewB().setVal(STOnOff.ON);
cTP.getPPr().getRPr().addNewColor().setVal("FF0000");
cTP.getPPr().getRPr().addNewSz().setVal(BigInteger.valueOf(40));
}
}
}
doc.write(new FileOutputStream("new document.docx"));
}
}
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP поставляется с пои-OOXML-схем-3.13. - * баночке.
Требование состоит в том, чтобы удалить весь текст, однако ячейка содержит только обычный текст без дополнительного контента, такого как изображения или даже пробелы, поэтому не имеет значения, удалю ли я текст или содержимое. Ваше решение кажется прекрасным, хотя оно дает мне «java.lang.NoClassDefFoundError: org/openxmlformats/schemas/wordprocessingml/x2006/main/impl/CTRowImpl $ 1TcList' в строке' CTTc [] cells = row.getCtRow(). GetTcList() .toArray (новый CTTc [0]); «Это странно, потому что у меня новая версия POI (3.13), и я добавил все файлы из двоичной версии. – Karatte
Импорт некоторых устаревших .jar работал с исключением, однако цикл вместе с содержимым удалял все границы таблицы. Я попытался исправить это с помощью 'table.setInsideHBorder (XWPFBorderType.SINGLE, 4, 0," 000000 ")', но это, очевидно, работает только с внутренними границами, поэтому внешние все еще невидимы. Также ориентация страницы вертикальна, в то время как она должна быть горизонтальной :( – Karatte
См. Мои приложения. Подходы удаляют полные ячейки. Поэтому, конечно, все стили ячеек будут удалены. Я предоставил теперь подход, который очищает только абзацы в ячейках и сохраняет стили ячеек с моим первым примером.Но как удаление и вставка ячеек таблицы влияет на ориентацию страницы, которую я не могу воспроизвести. –