title: C# Excel Interop Slow when looping through cells
body: <p>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 over all cells in the used range, extracting the text from each cell as I go. The problem is, this takes 14 seconds to execute.</p>
  
  <pre><code>public class ExcelFile
  {
      public string Path = @"C:\test.xlsx";
      private Excel.Application xl = new Excel.Application();
      private Excel.Workbook WB;
      public string FullText;
      private Excel.Range rng;
      private Dictionary&lt;string, string&gt; Variables;
      public ExcelFile()
      {
          WB = xl.Workbooks.Open(Path);
          xl.Visible = true;
          foreach (Excel.Worksheet CurrentWS in WB.Worksheets)
          {
              rng = CurrentWS.UsedRange;
              for (int i = 1; i &lt; rng.Count; i++)
              { FullText += rng.Cells[i].Value; }
          }
          WB.Close(false);
          xl.Quit();
      }
  }
  </code></pre>
  
  <p>Whereas in VBA I would do something like this, which takes ~1 second:</p>
  
  <pre><code>Sub run()
      Dim strText As String
      For Each ws In ActiveWorkbook.Sheets
          For Each c In ws.UsedRange
              strText = strText &amp; c.Text
          Next c
      Next ws
  End Sub
  </code></pre>
  
  <p>Or, even faster (less than 1 second):</p>
  
  <pre><code>Sub RunFast()
      Dim strText As String
      Dim varCells As Variant
      For Each ws In ActiveWorkbook.Sheets
          varCells = ws.UsedRange
          For i = 1 To UBound(varCells, 1)
              For j = 1 To UBound(varCells, 2)
                  strText = strText &amp; CStr(varCells(i, j))
              Next j
          Next i
      Next ws
  End Sub
  </code></pre>
  
  <p>Perhaps something is happening in the for loop in C# that I'm not aware of? Is it possible to load a range into an array-type object (as in my last example) to allow iteration over just the values, not the cell objects?</p>