I have an array of "transactions". My array looks like:
1, 12/15/18, 125.00, "phone bill"
2, 01/16/19, 37.25, "supplies"
3, 02/28/19, -50.00, "refund"
Write Array to Excel Range has good sample code that uses the line
[Excel]range.Value = arr
This works great if all my data types are the same. But they are not.
In Visual Basic (VB), it is easy to create an array of variants, and use the VB command
Worksheet.Range(UpperLeftCell).Resize(NumOfRangeRows, NumOfRangeColumns).Value = myArray
But I cannot find an equivalent in C#. Also I don't see how it is possible to create an array of variants in C#.
The best solution I can come up with is to split my array of transactions into 4 arrays: 1 for an integer, 1 for the date, 1 for the amount, and 1 for the description.
I could easily write each value individually to an Excel call, one at a time, but this is actually quite slow (I have thousands of transactions).
I am hoping someone can suggest a better way.
I have tried the code
Excel.Range range = arrayOfTrans;
but I get System.NotSupportedException: 'Operation is not supported. (0x80131515)'
This is the code I was looking for:
var data = new object[rows, columns]; // Each object can contain integers, strings, decimals, etc.
var startCell = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, 1];
var endCell = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[rows, columns];
var writeRange = worksheet.Range[startCell, endCell];
I was able to write 5 columns and 1,000 rows of data in 0.05 secs. – zerotax Apr 09 '22 at 16:42