Write array data to Excel range
When trying to write data from an array of objects to an Excel range, users may encounter an issue where each cell in the range receives the value of the first element of the array.
To solve this problem, instead of using rn_Temp.value2 = objData;
, use the following code:
<code class="language-csharp">object[,] arr = new object[objData.Length, 1]; for (int i = 0; i < objData.Length; i++) { arr[i, 0] = objData[i]; } rn_Temp.Value2 = arr;</code>
This method creates a two-dimensional array arr
with only one column and the same number of rows as the objData
array. Then assign the data to each row in arr
and set the rn_Temp
attribute of the Value2
to arr
.
Alternatively, if the input array is a multidimensional array, you can use the following code:
<code class="language-csharp">int rows = objData.GetLength(0); int cols = objData.GetLength(1); object[,] arr = new object[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { arr[i, j] = objData[i, j]; } } rn_Temp.Value2 = arr;</code>
This method effectively fills the required data into a specified range in Excel by creating a two-dimensional array from the input array and then assigning values to each individual element in the array.
The above is the detailed content of How to Write an Array of Objects to an Excel Range Correctly?. For more information, please follow other related articles on the PHP Chinese website!