Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Excel Range to C# Array

Tags:

arrays

c#

excel

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'."

like image 871
user3217843 Avatar asked Mar 31 '14 11:03

user3217843


People also ask

How do you convert a range in Excel?

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 do I convert Excel to CVC?

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.

Can you convert units in Excel?

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.

How do you convert a cell range to a table using a table style?

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.


1 Answers

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();

DebugExcel

like image 76
John Alexiou Avatar answered Sep 28 '22 00:09

John Alexiou