从excel中获取值并将其加载到字典中的性能问题
本文关键字:字典 性能 问题 加载 获取 excel | 更新日期: 2023-09-27 18:04:58
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);
}
}
包含8000行数据的excel文件(MyExcel.xls)。当我试图用上面的代码加载数据到字典,它需要很长时间来加载excel数据到字典。
比遍历范围内所有单元格更快的方法是:
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
}
}
可以只迭代指定的列,而不是迭代整个数组。