Free Support Forum - aspose.com

Word 2007 ~ Aspose Skip Empty Cell

Hi,

I am using Aspose with Word for a Mail Merge.

I have a 3x2 table as follows


However under certain conditions one field might be blank, if this is the case I'd like to ommit the entire cell - i.e. not just have an empty cell. i.e.


so in the above example c is empty and thus not displayed?

Can this be done?

I have tried IF and blank MERGEFIELDS also NextIf.
Hi,

Thank you very much for your inquiry.

Yes It can be done. You can use CellFormat.VerticalMerge property of any Cell for merging purpose. Please have a look here in the documentation reference to see how merging of Cells can be performed.

Following code snippet performs exactly what you require and should be helpful:

string dataDir = "C:\\Temp\\";

// Open an existing document.
Document doc = new Document(dataDir + “template.docx”);

// Fill the fields in the document with user data.
doc.MailMerge.Execute(
new string[] { “a”, “b”, “c”, “d”, “e”, “f” },
new object[] { “First”, “Second”, “”, “Fourth”, “Fifth”, “Sixth” });

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
foreach (Row row in table.Rows)
{
foreach (Cell cell in row.Cells)
{
String csValue = cell.GetText();

    <span style="color: green;">// Check if cell text is present or not.</span>
    <span style="color: blue;">if</span> (csValue == <span style="color: blue;">null</span> || csValue == <span style="color: rgb(163, 21, 21);">""</span> || csValue == <span style="color: rgb(163, 21, 21);">"\a"</span>)
    {
        <span style="color: rgb(43, 145, 175);">Row</span> nextRow = (<span style="color: rgb(43, 145, 175);">Row</span>)cell.ParentRow.NextSibling;
        <span style="color: blue;">if</span> (nextRow != <span style="color: blue;">null</span>)
        {
            <span style="color: rgb(43, 145, 175);">Cell</span> cellToMergeInto = (<span style="color: rgb(43, 145, 175);">Cell</span>)nextRow.Cells[cell.ParentRow.IndexOf(cell)].Clone(<span style="color: blue;">true</span>);
                        
            <span style="color: blue;">int</span> index = row.Cells.IndexOf(cell);
            row.Cells.RemoveAt(index);
            row.Cells.Insert(index, cellToMergeInto);

            nextRow.Cells.RemoveAt(index);
            nextRow.Cells.Insert(index, cell);

            cellToMergeInto.CellFormat.VerticalMerge = <span style="color: rgb(43, 145, 175);">CellMerge</span>.First;
            cell.CellFormat.VerticalMerge = <span style="color: rgb(43, 145, 175);">CellMerge</span>.Previous;
        }
    }
}

}
// Saved the document in Word format.
doc.Save(dataDir+“output.docx”);


Attached is the input template document named “template.docx” and output document named “output.docx”. Hope this helps. Please feel free to ask if you have any more queries.