I would like to convert an Excel Range to a C# Array with this code:
System.Array MyRange = (System.Array)range.cells.value;
for (int k = 0; k <= MyRange.Length; k++)
{
List<service_name> _ml = new List<service_name>();
for (int j = 1; j < dataitems.Count; j++)
{
// enter code here
}
}
And then iterate over it like in the above loop.
But this code does not work, and throws this Exception:
"Unable to cast object of type 'System.String' to type 'System.Array'."
Click anywhere in the table and then go to Table Tools > Design on the Ribbon. In the Tools group, click Convert to Range. Right-click the table, then in the shortcut menu, click Table > Convert to Range. Note: Table features are no longer available after you convert the table back to a range.
How to convert a XLS to a CSV file? Choose the XLS file that you want to convert. Select CSV as the the format you want to convert your XLS file to. Click "Convert" to convert your XLS file.
The Excel CONVERT function converts a number in one measurement system to another. For example, you can use CONVERT to convert feet into meters, pounds into kilograms, Fahrenheit to Celsius, gallons into liters, and for many other unit conversions.
You can also change the format for an existing table by selecting a different format. Select any cell within the table, or range of cells you want to format as a table. On the Home tab, click Format as Table. Click the table style that you want to use.
Based on the help provided my Microsoft here, this is how I read and write an array in Excel.
var xlApp=new Microsoft.Office.Interop.Excel.Application();
var wb=xlApp.Workbooks.Open(fn, ReadOnly: false);
xlApp.Visible=true;
var ws=wb.Worksheets[1] as Worksheet;
var r=ws.Range["A2"].Resize[100, 1];
var array=r.Value;
// array is object[1..100,1..1]
for(int i=1; i<=100; i++)
{
var text=array[i, 1] as string;
Debug.Print(text);
}
// to create an [1..100,1..1] array use
var array2=Array.CreateInstance(
typeof(object),
new int[] {100, 1},
new int[] {1, 1}) as object[,];
// fill array2
for(int i=1; i<=100; i++)
{
array2[i, 1] = string.Format("Text{0}",i);
}
r.Value2=array2;
wb.Close(SaveChanges: true);
xlApp.Quit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With