使用Microsoft.office.Interop.Excel读取Excel时性能下降

时间:2014-09-15 07:29:59

标签: c# excel performance

使用Microsoft.office.Interop.Excel从excel阅读并使用Range dataRange = (Range)cSheet.Cells[row, col];时,效果非常慢。当我删除Range dataRange = (Range)cSheet.Cells[row, col];时,速度更快。我错过了什么。我应该改变什么?

int rows = cSheet.UsedRange.Rows.Count;
int cols = cSheet.UsedRange.Columns.Count;

for (int row = 2; row <= rows; row++)
{
  for (int col = 1; col <= cols; col++)
  {
        Range dataRange = (Range)cSheet.Cells[row, col];
  }
}

1 个答案:

答案 0 :(得分:4)

您希望在一次操作中执行此操作:

object[,] objectArray = cSheet.get_Range("A1:C4").Value2;
dataRange.Value2 = objectArray;

要获取“A1:C4”的UsedRange地址,请尝试:

Microsoft.Office.Interop.Excel.Range range = cSheet.UsedRange;
string address = range.get_Address();
string[] cells = address.Split(new char[] {':'});
string beginCell = cells[0].Replace("$", "");
string endCell = cells[1].Replace("$", "");