I am using Microsoft.Office.Interop.Word
and want to output a given database as a table in a Word document. But after my first attempts (example below), I quickly noticed that the time to iterate over each table row increases rapidly with the number of rows.
using Word = Microsoft.Office.Interop.Word;
private void InsertTableWithRandomValue(Word.Document doc)
{
var par = doc.Paragraphs.Add();
string guid = Guid.NewGuid().ToString();
Word.Table firstTable = doc.Tables.Add(par.Range, 1000, 5);
firstTable.Borders.Enable = 1;
foreach (Word.Row row in firstTable.Rows)
{
foreach (Word.Cell cell in row.Cells)
{
cell.Range.Text = guid;
}
}
}
In a table with 200 rows it takes about 100ms to write each entry. With 2000 rows however, it is already up to 400ms per entry, which is not fast enough for my use case.
Is there a way to iterate over each row faster?
If not, my next approach would be to temporarily save the Word document as HTML, edit the text, and export it again as a Word document.
Office Interop is really slow. You should consider using Open XML to create documents.
I've created an example from your code. First, add
DocumentFormat.OpenXml
NuGet package to your project.