Combining Tables

Dear Aspose Team,

I’m currently migrating our code from “aspose.words 11” to “aspose.words 26.2”.
I know, it’s a big version jump. :slight_smile: I’m running into a problem and hope you can help. We have a method to merge two tables into one.
It’s important that the widths of the individual columns in the old tables are preserved.
Unfortunately, this is no longer the case. Therefore, the result is unusable.

Our previous code was very simple:

Table Tab2 = doc.LastSection.Body.Tables[doc.LastSection.Body.Tables.Count - 1];
Table Tab1 = doc.LastSection.Body.Tables[doc.LastSection.Body.Tables.Count - 2];
if (Tab2 != null && Tab1 != null)
{
  while (Tab2.HasChildNodes)
     Tab1.Rows.Add(Tab2.FirstRow);
}
Tab2.Remove();

Do you have any ideas about what we should do differently?

Thank you
Kind regards, Henry

@HenryE Just let Aspose.Words to join the tables. Aspose.Words automatically joins the tables if there are no other nodes between them, just like MS Word does. Please try using the following code:

Document doc = new Document(@"C:\Temp\in.docx");

Table Tab2 = doc.LastSection.Body.Tables[doc.LastSection.Body.Tables.Count - 1];
Table Tab1 = doc.LastSection.Body.Tables[doc.LastSection.Body.Tables.Count - 2];
if (Tab2 != null && Tab1 != null)
    Tab1.ParentNode.InsertAfter(Tab2, Tab1);
            
// After saving the document the tables will be joined into one table.
doc.Save(@"C:\Temp\out.docx");

Thank you very much. That’s working a bit better. When does the actual merging of the tables occur? After your command, there are still two tables. So the number of tables remains the same. We have numerous operations that we perform on the document. For this, it’s important that after the initial merge, the result of the first merge is ONE table.

I’ve been experimenting with your code. Sometimes it works, but mostly it doesn’t. Please try it with the attached document. It contains two tables that I want to merge without changing the width of the individual cells. Unfortunately, this isn’t working. Do I need to set a property in the tables to prevent them from automatically resize?

Problem_Combine_Tables.docx (36.3 KB)

Problem_Combine_Tables_Output.docx (29.4 KB)

@HenryE

Actual table merging occurs on document save.

You can try autofitting the table before merging them. For example see the following code:

Document doc = new Document(@"C:\Temp\in.docx");

Table Tab2 = doc.LastSection.Body.Tables[doc.LastSection.Body.Tables.Count - 1];
Tab2.AutoFit(AutoFitBehavior.AutoFitToWindow);
Table Tab1 = doc.LastSection.Body.Tables[doc.LastSection.Body.Tables.Count - 2];
Tab1.AutoFit(AutoFitBehavior.AutoFitToWindow);
if (Tab2 != null && Tab1 != null)
    Tab1.ParentNode.InsertAfter(Tab2, Tab1);

// After saving the document the tables will be joined into one table.
doc.Save(@"C:\Temp\out.docx");

this code gives better result for the attached documents:
out.docx (29.4 KB)