Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Excel range to a List<String>?

Tags:

c#

excel

I'd like to get a list of strings from an Excel range where the data could be mixed types (strings, doubles, etc.). I tried using this:

List<string> rangeToList(Excel.Range inputRng)
    {
        object[,] cellValues = (object[,])inputRng.Value2;
        List<string> lst = cellValues.Cast<string>().ToList();
        return lst;
    }

But the line with Cast<string> returns this error:

Unable to cast object of type 'System.Double' to type 'System.String'

How can I convert this array of objects into my desired list?

like image 373
sigil Avatar asked Mar 06 '14 20:03

sigil


Video Answer


2 Answers

First you should cast to object to make list of object and after that you should use ConvertAll (msdn) to convert object to string.

List<string> rangeToList(Microsoft.Office.Interop.Excel.Range inputRng)
{
    object[,] cellValues = (object[,])inputRng.Value2;
    List<string> lst = cellValues.Cast<object>().ToList().ConvertAll(x=> Convert.ToString(x));
    return lst;
}
like image 149
kmatyaszek Avatar answered Oct 24 '22 19:10

kmatyaszek


Cast won't implicitly convert a number to a string, but you can call ToString on each object:

List<string> lst = cellValues.Cast<object>()
                             .Select(o => o.ToString())
                             .ToList();
like image 38
D Stanley Avatar answered Oct 24 '22 20:10

D Stanley