在Winforms应用程序中使用Excel Interop缓慢写入Excel单元格

问题描述

我正在寻找有关将数据写入Excel工作表的代码的帮助。 我目前正在一次将数据写入单个单元格,每个单元格大约需要三秒钟。您可以想象,当您开始进入数百个细胞时,这个时间真的开始增加

我知道有一种保存到一定范围的单元格的方法,但并不完全确定该怎么做。

我要写的文档是一个调查表样式的电子表格,其中包含以下列:数字,问题,是,否,不适用。 我遍历用户控件列表,这些控件保存了用户从表单中选择的答案,然后将其写入单元格。

任何帮助表示感谢,谢谢。

if (QuestionList.Count > 0)
{
                    //loop round rows
                    for (int i = 0; i < QuestionList.Count; i++)
                    {
                        //check that index is not null
                        if (!String.IsNullOrEmpty(QuestionList[i].Index))
                        {
                            //if the char in index is a letter
                            if (Char.IsLetter(QuestionList[i].Index[0]))
                            {
                                worksheet2.Cells[i + 1,4].Value2 = QuestionList[i].Yes;
                                worksheet2.Cells[i + 1,5].Value2 = QuestionList[i].No;
                                worksheet2.Cells[i + 1,6].Value2 = QuestionList[i].NA;
                            }
                        }
                    }
                }

解决方法

一次性读取多个单元格值的简单方法是创建一个新的Excel范围,指定要读取的单元格范围。 然后,您可以将范围内的值放入一个多维对象数组中。 然后只需返回数组中的单元格位置即可获取值。

这将执行一次读取以获取多个单元格值,而不是对每个单元格进行一次读取。

    string name;
    string dob;
    string address; 

    //excel range
    Excel.Range range = (Excel.Range)xlWorksheet1.Range["A1","I10"];
    //range array
    object[,] rangeValueArray = range.Value2;
    
    //cell 1A
    if (rangeValueArray[1,1] != null)
    {
             name = rangeValueArray[1,1].ToString();
    }
    
    //cell 1B
    if (rangeValueArray[1,2] != null)
    {
             dob = rangeValueArray[1,2].ToString();
    }
    
    //cell 1C
    if (rangeValueArray[1,3] != null)
    {
             address = rangeValueArray[1,3].ToString();
    }