Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to write cells to Excel with Office Interop?

I am writing a function to export data to Excel using the Office Interop in VB .NET. I am currently writing the cells directly using the Excel worksheet's Cells() method:

worksheet.Cells(rowIndex, colIndex) = data(rowIndex)(colIndex)

This is taking a long time for large amounts of data. Is there a faster way to write a lot of data to Excel at once? Would doing something with ranges be faster?

like image 683
davidscolgan Avatar asked Jun 22 '10 18:06

davidscolgan


People also ask

Is OpenXML faster than Interop?

Probably yes, but it really depends on the complexity of the sheet. It is more efficient to use OpenXML SDK then Interop, but the code is a bit more complicated. Also both OpenXML SDK and Excel Interop are third party libraries. If you do not want to use any third party library then you would need to use System.


2 Answers

You should avoid reading and writing cell by cell if you can. It is much faster to work with arrays, and read or write entire blocks at once. I wrote a post a while back on reading from worksheets using C#; basically, the same code works the other way around (see below), and will run much faster, especially with larger blocks of data.

  var sheet = (Worksheet)Application.ActiveSheet;
  var range = sheet.get_Range("A1", "B2");
  var data = new string[3,3];
  data[0, 0] = "A1";
  data[0, 1] = "B1";
  data[1, 0] = "A2";
  data[1, 1] = "B2";
  range.Value2 = data;
like image 68
Mathias Avatar answered Nov 07 '22 07:11

Mathias


If you haven't already, make sure to set Application.ScreenUpdating = false before you start to output your data. This will make things go much faster. The set it back to True when you are done outputting your data. Having to redraw the screen on each cell change takes a good bit of time, bypassing this saves that.

As for using ranges, you still will need to target 1 (one) specific cell for a value, so I see no benefit here. I am not aware of doing this any faster than what you are doing in regards to actually outputting the data.

like image 26
Tommy Avatar answered Nov 07 '22 05:11

Tommy