如何将Excel范围转换为List< String&gt ;? [英] How to convert an Excel range to a List<String>?

查看:413
本文介绍了如何将Excel范围转换为List< String&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个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;
    }

但是带有Cast<string>的行返回此错误:

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?

推荐答案

Cast不会将数字隐式转换为字符串,但是您可以在每个对象上调用ToString:

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

这篇关于如何将Excel范围转换为List&lt; String&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆