Writing a 2-dimensional array to a range

I am trying to write data to a range of cells. I create a range containing those cells and then try to write a 2-dimensional array to the Value member of the range:


Dim wb As Workbook = new Workbook()

Dim ws As Worksheet = wb.Worksheets(“Sheet1”)

Dim theRange As Range = ws.Cells.CreateRange(“A1”, “B2”)

theRange.Value = GetData() ’ GetData() returns a 2-by-2 array

I get an ArgumentException when the last line of the above code executes. It complains that “Array was not a one-dimensional array”. So I tried using a one-dimensional array, but I got an ArrayIndexOutOfBound exception.

According to the documentation on the Value member of the Range class:
"If the range contains multiple cells, return a two-dimension Array
object. If applies object array to the range, it should be a two-dimension
Array object."

I am using a two-dimensional array like the documentation says, but I can’t get it to work. I am just wondering if anyone has ever gotten it to work. The alternative for me is to loop over the cells in the range and set them one by one, but that’s slower.

Thanks.

Ray



Hi,

Thanks for your posting and considering Aspose.Cells for .NET.

Please use the following code with to import a 2-Dimensional Array.

Please download and use the latest version:
Aspose.Cells
for .NET v7.1.1.5



Please also see this article for your reference: Importing Data to Worksheets

I have also attached the output file generated by this code and also you can see the screenshot.

VB.NET


'Create a workbook

Dim workbook As Workbook = New Workbook()


Dim arrStrings(,) As String = {{“hello”, “hi”, “yes”}, {“tell”, “say”, “no”}}


'Import array at cell A1

workbook.Worksheets(0).Cells.ImportArray(arrStrings, 0, 0)


workbook.Save(“F:\Shak-Data-RW\Downloads\output.xlsx”)


Screenshot: