I have a word template that has multiple similar tables and some paragraphs associated to those tables placed just before them. Depending on the amount of data, I populate some tables and others are not required, so are there paragraphs.
I need to remove these tables and paragraphs.
As you can see in the image, I need to remove Table 2 and its paragraph Table Parahgraph
Please help me how to do it. I tried using document.removeBodyElement(pos) , but it does not help.
int startIndex = 0;
int endIndex = 0;
startIndex = doc.getPosOfTable(doc.getTables().get(0));
startIndex++;
endIndex = doc.getPosOfTable(doc.getTables().get(1));
System.out.println("startIndex "+ startIndex);
System.out.println("endIndex "+ endIndex);
for(int i=startIndex; i<=endIndex; i++){
doc.removeBodyElement(i);
The problem is that using removeBodyElement shifts the rest of the elements and recalculates their indices. It means, that if you want to delete elements #4 to #6 (empty paragraph between two tables is included), then after deleting the element #4 (empty line), it is your second TABLE (and not its title paragraph) that will become the element #5, etc. Basically, this loop becomes jumping by two elements (i+=2 instead of i++), thus deleting only half of what you want, and even deleting something you don't want to delete.
Thus, you have just to reverse the order of your loop:
for ( int i = endIndex; i >= startIndex; i-- ) {
System.out.println( "removing bodyElement #" + i );
document.removeBodyElement( i );
I've tested it with a template, similar to your example, it works fine! Hope it helps.
I have a word template that has multiple similar tables and some paragraphs associated to those tables placed just before them. Depending on the amount of data, I populate some tables and others are n...
WordUtil.createSimpleWord(file, word);//file 对应的文件模板,word传递参数的实体对象
List<XWPFParagraph> paragraphs = doc.getParagraphs();
Int...
从
poi
4.0.0开始,在sheet里面提供了一个shiftColumns(int startColumn, int endColumn, final int n)api,
移动开始列、结束列和移动列数。
需要注意的是,
移动到的列需要没有格式的空白列。
n>0向左移动,n<0向右移动。
poi
4.0.0至4.1.2存在bug,无法同步移动列的合并格式。但是在最新的5.0.0版本
中
重写修复了这个bug。
目标列需要是无内容的空白列,
public static void changeText(XWPFDocument document){
//获取文字
段落
集合
List<XWPFParagraph> paragraphs = document.getParagraphs();
//所有类型集合(文字
段落
、
表格
、图片等)
List<IBodyEl
非常好的问题!Springboot可以
使用
Apache
POI
库来读取Word文档
中
的文字和
表格
。您可以
使用
XWPFDocument类来打开Word文档,然后
使用
XWPFParagraph类和XWPFTable类来读取文本和
表格
。以下是一个简单的示例代码:
FileInputStream fis = new FileInputStream(new File("example.
docx
"));
XWPFDocument document = new XWPFDocument(fis);
// 读取文本
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph para : paragraphs) {
System.out.println(para.getText());
// 读取
表格
List<XWPFTable> tables = document.getTables();
for (XWPFTable table : tables) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
System.out.println(cell.getText());
document.close();
希望这可以帮助您开始
使用
Apache
POI
库来读取Word文档
中
的文字和
表格
!