yammerade
yammerade

Reputation: 629

More than 15 columns in Novacode DocX Table

Is there a way to create a word table with more than 15 columns using Novacode DocX?

If I create a new table with greater than 14 columns, the table doesn't appear. I can get around this by doing something like this:

int addCols = Math.Min(data.colCount, 14);
Table docTable = doc.InsertTable(data.rowCount, addCols);

And then later this:

docTable.InsertColumn();

However, if I try to do this more than once to create a table with 16 or more columns, I have the same issue where the table doesn't appear.

Is there any way around this?

Upvotes: 1

Views: 2720

Answers (2)

Daniel
Daniel

Reputation: 103

There is something like a bug in the library. When you create a table with many columns it becomes unusable. Reason is, that each column is created with its initial width. When you create table (independatly of the used method: InsertTable, AddTable, InsertTableBeforeSelf etc.) with many columns and the sum of their widths exceeds the document width - the table becomes unusable.

I solved this problem by adding columns in cycle and decreasing their width. My code is similar to this:

private void CreateSampleTable(DocX document)
{
    int rowsCount = 10;
    int columnsCount = 20;
    int columnWidth = 30;

    Table sampleTable = document.AddTable(rowsCount, 1);
    foreach (Row row in sampleTable.Rows)
    {
        row.Cells[0].Width = columnWidth;
    }

    for (int colIndex = 1; colIndex < columnsCount; colIndex++)
    {
        sampleTable.InsertColumn(colIndex);
        foreach (Row row in sampleTable.Rows)
        {
            row.Cells[colIndex].Width = columnWidth;
        }
    }

    Paragraph par = document.InsertParagraph();
    par.InsertTableBeforeSelf(sampleTable);
}

Upvotes: 1

Phillip
Phillip

Reputation: 255

Here is my way around this. This might not work if you need many different tables with random large numbers of columns because it would take a lot of work.

using (DocX template = DocX.Load("template.docx"))
{
     Novacode.Table tempTable;
     using (DocX template2 = DocX.Load("template2.docx"))
     {
          tempTable = template2.Tables[0];
     }
     Novacode.Table t1 = doc.InsertTable(tempTable);
     t1.InsertRow();
     t1.InsertRow();
     template.Save();
}

This is a possible solution. template is the DocX you are inserting a Table into. template2 contains pre-made Tables that are 1 row and have as many columns as you would like. So template2.Table[0] would be a Table size (1,15). You can then add more Tables to template2 (outside of code by creating them within the document in Microsoft Word) growing larger: template2.Table[1] would be a Table size (1,16). The only issue is if you have a lot of different number of column Tables that you need to work with. Novacode-dox is not a very good library for building things from scratch.

Hope this might be a work around for you.

Upvotes: 1

Related Questions