This project has moved and is read-only. For the latest updates, please go here.

Row.MergeCells(int, int) appends empty paragraphs

Mar 9, 2011 at 7:16 AM

Let's say I have this table:

Header1 Header2 Header3
Value    

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:

Value

 

 

instead of

Value

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())
    {
        element.Remove();
    }
}

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

 

Aug 11, 2012 at 12:53 AM
Edited Aug 11, 2012 at 12:54 AM

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 4: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 2:22 PM
Edited Jun 28, 2013 at 2: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.

                    invoice_table.Rows[i].Cells[1].Paragraphs[0].Remove(false);
                }
            }