Frage

I have an excel sheet returning back the Interop Excel Range in c#. What I am trying to do is cast the range.Value2 which comes back as rangeVal2 as [1,1] int [1,2] string [1,3] null. I wanted to know how can I convert Interop.range Value2 to a one dimensional string array[] This is from the watch returning Range.Value2

[1, 1] "Somestring" object {string}
[1, 2]  null    object
[1, 3]  null    object
[1, 4]  null    object
[1, 5]  0.0 object {double}
[1, 6]  0.0 object {double}
[1, 7]  0.0 object {double}
War es hilfreich?

Lösung

Not sure what you have, but try

string[] arr = oRngListRow.Value2.Cast<object>()
    .Select(x => x == null ? null : x.ToString()).ToArray();

close to what you had in your own comment.


Since C# 6.0 (from 2015), this can also be written:

string[] arr = oRngListRow.Value2.Cast<object>()
    .Select(x => x?.ToString()).ToArray();

If you want an empty string instead, in the case where the entry is a null object, you can use string interpolation, also since C# 6.0:

string[] arr = oRngListRow.Value2.Cast<object>()
    .Select(x => $"{x}").ToArray();

Andere Tipps

Please try the following. For some reason, Excel Interop does not like Linq.

        var list = new List<string>();

        for (int i = 1; i <= 7; i++)
        {
            list.Add((oRngListRow.Cells[1, i].Value2 ?? string.Empty).ToString());
        }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top