C# Efficient way to iterate over excel worksheet

て烟熏妆下的殇ゞ 提交于 2020-01-02 10:26:14

问题


I have the following code:

string result = "";
for(int i=2; i<=excelRange.Rows.Count; i++)
{
    result += excelRange.Cells[i, 2].Value2;
}

For an excel file with a couple hundred entries this takes 5 seconds. Is there a more efficient way, perhaps? I only want the values from B2 to Bn.


回答1:


Yes, there is a more efficient way.

  1. Create a range that exactly matches the cells that you really need.

  2. Get the Value2 property of this range. The result will be an array type.

  3. Iterate through the array

The problem with your approach is the large number of inter-process requests between your application and Excel. Your approach requires two or three requests per cell. The proposed approach is much faster because it requires a few requests up-front but not additional requests per cell.

Note that this works up to about 4000 cells. If you need to process more cells, you will need to split it into several ranges, each one containing less than 4000 cells.

Update

Assuming Excel is already running, it would look something like this (the correct number of rows in the B column is automatically selected):

var excelApp =  (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
var range = (Excel.Range)workSheet.Range[workSheet.Range["B2"],
        workSheet.Range["B2"].End[Excel.XlDirection.xlDown]];
var cellData = (Object[,])range.Value2;

string result = "";
foreach (var cell in cellData) {
    result += cell.ToString();
}



回答2:


The basic skeleton is the following:

var xlApp = new Excel.Application { Visible = true };
var xlBook = xlApp.Workbooks.Open(@"C:\Temp\Results.xlsx");
var xlSheet = xlBook.Sheets[1] as Excel.Worksheet;
var arr = (object[,])xlSheet.Range["B2:B100000"].Value;
var sb = new StringBuilder();
for (int x = 1; x <= arr.GetUpperBound(0); ++x)
{
    sb.Append(arr[x, 1]);
}
var final_string = sb.ToString();

// Close workbook, close Excel...


来源:https://stackoverflow.com/questions/53583879/c-sharp-efficient-way-to-iterate-over-excel-worksheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!