在 C# 中填充单词 table 的最快方法?

Fastest way to populate word table in c#?

目前,我是通过for循环来完成的。但是,我的 table 有 58 行和 13 列,保存 word 文档需要大约 20 秒。有没有更好的方法用数据填充单词 table?

        for (int i = 1; i<58; i++)
        {
            document.Tables[2].Columns[4].Cells[i].Range.Text = form.report[i].debInfo.value1.ToString();
            document.Tables[2].Columns[5].Cells[i].Range.Text = form.report[i].debInfo.value2.ToString();
            document.Tables[2].Columns[6].Cells[i].Range.Text = form.report[i].debInfo.value3.ToString();
            document.Tables[2].Columns[7].Cells[i].Range.Text = form.report[i].debInfo.value4.ToString();
            document.Tables[2].Columns[8].Cells[i].Range.Text = form.report[i].kredInfo.value1.ToString();
            document.Tables[2].Columns[9].Cells[i].Range.Text = form.report[i].kredInfo.value2.ToString();
            document.Tables[2].Columns[10].Cells[i].Range.Text = form.report[i].kredInfo.value3.ToString();
            document.Tables[2].Columns[11].Cells[i].Range.Text = form.report[i].kredInfo.value4.ToString();
            document.Tables[2].Columns[12].Cells[i].Range.Text = form.report[i].kredInfo.value5.ToString();
            document.Tables[2].Columns[13].Cells[i].Range.Text = form.report[i].value.ToString();
        }

刚刚检查了我的 "save to word" 方法的执行时间,执行大约需要 12 秒。 For 循环需要 ~5 秒,另外 ~6-7 秒用于生成 word 文档。

我试过 this article:

中的代码
const int NumRows = 58;
const int NumCols = 13;
object objMiss = System.Reflection.Missing.Value;
objTab1 = objDoc.Tables.Add(objWordRng, NumRows, NumCols,
                        ref objMiss, ref objMiss); //add table object in word document
objTab1.Range.ParagraphFormat.SpaceAfter = 6;
int iRow, iCols;
string strText;

for (iRow = 1; iRow <= NumRows; iRow++)
    for (iCols = 1; iCols <= NumCols; iCols++)
       {
           strText = "row:" + iRow + "col:" + iCols;
           objTab1.Cell(iRow, iCols).Range.Text = strText; //add some text to cell
       }

在可见模式下需要 4s 的运行时间,在 objApp.visible = false 下需要 2s

您的代码变慢的原因可能是您在每一行中解析对象引用链。

而不是写作

document.Tables[2].Columns[4].Cells[i].Range.Text = form.report[i].debInfo.value1.ToString();

尝试将经常使用的对象引用存储在辅助数组中。在此示例中,对每一行重新计算 document.Tables[2].Columns[4]。您可以评估一次并将其存储在本地数组中。 COM 对象属性的评估涉及大量后台处理,而且速度非常慢。

可能还有其他技巧可以加速 Word COM 对象。在 Excel 中,关闭显示更新有很大的不同。添加 table 个单元格时应暂停 Word 布局呈现。但是我不知道该怎么做。

我发现使用 Range.ConvertToTable 方法

Range r = doc.Paragraphs.Add().Range;

string s = string.Join("\n", data.Select(a => string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}",a.Item1,a.Item2,a.Item3,a.Item4,a.Item5,a.Item6,a.Item7)));

r.Text = s;

Table t = r.ConvertToTable(Separator: WdTableFieldSeparator.wdSeparateByTabs);