This project has moved. For the latest updates, please go here.

Table with 1000+ rows performs slow

Aug 31, 2015 at 10:38 PM
I'm evaluating DocX to export a DataTable To Word. It Works really well until the DataTable contains more than a few hundred rows. When it does the export is slow. Here is the code I'm using. Any help is appreciated.
Private Sub ExportToWordTest(dt As DataTable, FileName As String)

    Using document As DocX = DocX.Create(FileName)
        ' Create table
        Dim tbl As Table = document.InsertTable(dt.Rows.Count + 1, dt.Columns.Count)


        ' Add header row
        For Each dc As DataColumn In dt.Columns
            tbl.Rows(0).Cells(dc.Ordinal).Paragraphs.Item(0).InsertText(dc.ColumnName, False)
        Next

        ' Loop through the rows in the Table and insert data from the data source.
        For row As Integer = 1 To tbl.RowCount - 1
            For cell As Integer = 0 To tbl.Rows(row).Cells.Count - 1
                ' Add data to cell
                tbl.Rows(row).Cells(cell).Paragraphs.Item(0).InsertText(dt.Rows(row - 1).ItemArray(cell).ToString(), False)
            Next
        Next

        ' Save the document.
        document.Save()
    End Using
End Sub
Sep 1, 2015 at 5:24 PM
Change code based on this example http://cathalscorner.blogspot.com/2010/06/docx-and-tables.html and it works faster now. Basically using AddTable instead of InsertTable and Append instead of InsertText. Here is the new code:
Private Sub ExportToWordTest(dt As DataTable, FileName As String)

    Using document As DocX = DocX.Create(FileName)
        ' Create table
        Dim tbl As Table = document.AddTable(dt.Rows.Count + 1, dt.Columns.Count)

        ' Add header row
        For Each dc As DataColumn In dt.Columns
            tbl.Rows(0).Cells(dc.Ordinal).Paragraphs.First.Append(dc.ColumnName)
        Next

        ' Loop through the rows in the Table and insert data from the data source.
        For row As Integer = 1 To tbl.RowCount - 1
            For cell As Integer = 0 To tbl.Rows(row).Cells.Count - 1
                ' Add data to cell
                tbl.Rows(row).Cells(cell).Paragraphs.First.Append(dt.Rows(row - 1).ItemArray(cell).ToString())
            Next
        Next

        'Insert Table into Document
        document.InsertTable(tbl)

        ' Save the document.
        document.Save()
    End Using
End Sub