0
private void btnImportFromxls_Click(object sender, RoutedEventArgs e)
    {
        Excel.Application myapp = new Excel.Application();
        Excel.Workbook wb = myapp.Workbooks.Open(@"D:\MyExcel.xls");
        Excel.Worksheet sheet = (Excel.Worksheet)wb.Worksheets.get_Item(1);
        Dictionary<object, object> dictionary = new Dictionary<object, object>();
        for (int i = 1; i < sheet.UsedRange.Rows.Count; i++)
        {
            object key = ((Excel.Range)sheet.Cells[i, 1]).Value2;
            object value = ((Excel.Range)sheet.Cells[i, 2]).Value2;

            dictionary.Add(key,value);
        }
    }

具有 8,000 行数据的 excel 文件(MyExcel.xls)。当我尝试使用上述代码将数据加载到字典中时,将 excel 数据加载到字典中需要很长时间。有没有其他方法可以加快将数据加载到字典中?

4

1 回答 1

1

比遍历范围内的所有单元格更快的是:

using XLS = Microsoft.Office.Interop.Excel;

object[,] arrWks;
object objKom;
string strKom;

arrWks = (object[,])sheet.UsedRange.get_Value(XLS.XlRangeValueDataType.xlRangeValueDefault);

for (int intRow=arrWks.GetLowerBound(0); intRow<=arrWks.GetUpperBound(0); intRow++)
{
    for (int intCol=arrWks.GetLowerBound(1); intCol<=arrWks.GetUpperBound(1); intCol++)
    {
        objKom = arrWks[intRow, intCol];
        strKom = objKom == null ? "" : objKom.ToString();       

        //do rest of your logic here
    }
}

您也可以只遍历指定的列,而不是迭代整个 arrWks。

于 2013-03-21T13:01:19.287 回答