C# Excel Interop Slow when looping through cells

后端 未结 4 781
星月不相逢
星月不相逢 2021-02-06 05:38

I am trying to extract all text data from an Excel document in C# and am having performance issues. In the following code I open the Workbook, loop over all worksheets, and loop

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-06 06:02

    I use this function. The loops are only for converting to array starting at index 0, the main work is done in object[,] tmp = range.Value.

    public object[,] GetTable(int row, int col, int width, int height)
    {
        object[,] arr = new object[height, width];
    
        Range c1 = (Range)Worksheet.Cells[row + 1, col + 1];
        Range c2 = (Range)Worksheet.Cells[row + height, col + width];
        Range range = Worksheet.get_Range(c1, c2);
    
        object[,] tmp = range.Value;
    
        for (int i = 0; i < height; ++i)
        {
            for (int j = 0; j < width; ++j)
            {
                arr[i, j] = tmp[i + tmp.GetLowerBound(0), j + tmp.GetLowerBound(1)];
            }
        }                 
    
        return arr;
    }
    

提交回复
热议问题