How to remove tables and paragraphs containing data from docx in java using apache poi

后端 未结 1 1493
傲寒
傲寒 2021-01-15 14:19

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 s

相关标签:
1条回答
  • 2021-01-15 15:06

    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.

    0 讨论(0)
提交回复
热议问题