Row.MergeCells(int, int) appends empty paragraphs

Mar 9, 2011 at 6:16 AM

Let's say I have this table:

Header1 Header2 Header3

If I do a table.Rows[1].MergeCells(0,2), the (empty) paragraphs from cells (1,1) and (1,2) will be appended to the merged cell.

The resulting cell looks something like this:




instead of


as I normally get if I merge celles in in a word processor.

I tried to remove the empty lines with Paragraph.Remove(), Paragraph.RemoveText(), and variations of Cell.Paragraphs.Remove(). But since Cell.Paragraphs is newed up based on the XML on every get, there is no use in manipulating this collection.

Luckily the DocXElement has read and write access to the Xml-property (XElement), which I used to work around the problem in my document-generator:

private static void RemoveEmptyParagraphsFrom(DocXElement cell)
    var xml = cell.Xml;
    foreach (var element in xml.Elements(Paragraph).Where(e => string.IsNullOrWhiteSpace(e.Value)).ToList())

Don't forget the ToList()-call, or else you will end up trying to modify the collection you are enumerating over.


Aug 10, 2012 at 11:53 PM
Edited Aug 10, 2012 at 11:54 PM

I had the same issue but your solution did not work for me.

After merging cells I was able to remove the last empty paragraph with the following call. 


firstCell.Paragraphs.Last().Remove( false);

Dec 12, 2012 at 3:52 PM

I have the same issue in v1.0.0.11, merging cells results in empty paragraphs.  The solution lofum posted worked, although this isn't ideal behavior.

Jun 28, 2013 at 1:22 PM
Edited Jun 28, 2013 at 1:23 PM
Here's another approach that worked for me. I think is pretty simple and efficient.
            int LastRow = *SomeValue*;

            for (int i = 0; i < LastRow; i++)
                invoice_table.Rows[i].MergeCells(1, 3);
                int paraCount = invoice_table.Rows[i].Cells[1].Paragraphs.Count;

                //Set k = 1 to leave one paragraph to be used.
                for (int k = 1; k < paraCount; k++)
                    //Note that you need to set the paragraph's index to 0 
                    //since each time a paragraph is removed the indexes are reset.