Merge nested tables

Hi,

First of all, I’m using Aspose.Words 16.1.

I’m trying to merge a nested table into its parent one. But for some reasons, I can’t get the merged cells to fit correctly.

Please find below the code to reproduce with the attached documents:

public static void mergeTableRepro() throws Exception {
    Document document = new Document("nested tables.docx");
    NodeCollection<?> tables = document.getChildNodes(NodeType.TABLE, true);
    Table fromTable = (Table) tables.get(1);
    Table toTable = (Table) tables.get(0);
    Row toRow = toTable.getFirstRow();
    toRow.getLastCell().remove();
    Cell firstCellFromTable = fromTable.getFirstRow().getFirstCell();
    firstCellFromTable.getCellFormat().setPreferredWidth(PreferredWidth.fromPercent(16.7));
    toRow.appendChild(firstCellFromTable);
    Cell secondCellFromTable = fromTable.getFirstRow().getFirstCell();
    secondCellFromTable.getCellFormat().setPreferredWidth(PreferredWidth.fromPercent(16.7));
    toRow.appendChild(secondCellFromTable);
    document.save("merged tables.docx");
}

Thanks for your help.

Best regards,

Hi David,

Thanks for your inquiry. Could you please also attach your expected Word document here for our reference? We will investigate the structure of your expected document as to how you want your final output be generated like. You can create expected document using Microsoft Word. We will then provide you code to achieve the same using Aspose.Words for Java.

Best regards,

Hi Awais,

Thank you for your answer.

As requested, you can find attached the expection result.

Basically, what I need to do is copy all the cells of a nested table in their enclosing/parent table.

Please let me know if you need any further information.

Thank you very much.

Best regards,

Hi David,

Thanks for your inquiry. Please try using the following code to get expected output:

Document document = new Document(getMyDir() + "nested tables.docx");

NodeCollection <?> tables = document.getChildNodes(NodeType.TABLE, true);

Table fromTable = (Table)tables.get(1);
Table toTable = (Table)tables.get(0);

Row toRow = toTable.getFirstRow();

toTable.setAllowAutoFit(false);
double width = (toRow.getLastCell().getCellFormat().getWidth() / 2);

toRow.getLastCell().remove();

Cell firstCellFromTable = fromTable.getFirstRow().getFirstCell();
firstCellFromTable.getCellFormat().setWidth(width);

toRow.appendChild(firstCellFromTable);

Cell secondCellFromTable = fromTable.getFirstRow().getFirstCell();
secondCellFromTable.getCellFormat().setWidth(width);

toRow.appendChild(secondCellFromTable);

document.save(getMyDir() + "awjava-16.1.0.docx");

Hope, this helps.

Best regards,