将Excel互操作的Range.Value2转换为字符串 [英] Casting Range.Value2 of Excel interop to string
问题描述
我从C#应用程序的Excel工作表中导入一些值。一栏基本上是文本,但可以包含任何值。我使用了以下内容:
I import some values from Excel sheets in C# application. One column is a text basically but can contain any values. I used the following:
Range range = ... // getting this from Excel, works fine
string myString = (string)range.Value2;
当单元格中包含文本时,此方法有效。但是当它包含例如123时,调试器将显示123.0的range.Value2值,并且转换为字符串失败,并带有异常。
When the cell contains text, this is working. But when it contains, for example, 123, the debugger shows 123.0 for range.Value2 and conversion to string fails with exception.
我想知道如何为所有类型的单元格编写最通用的转换。至少字符串和整数可能是浮点型内容。
I wonder, how to write the most general conversion for all kinds of cells. At least string and integer, may be float content.
推荐答案
我发现解决方案可能不太好,但可行: / p>
I found the solution which may be not so nice but works:
myString = range.Value2 == null ? "" : range.Value2.ToString();
可能存在更好的东西。
这篇关于将Excel互操作的Range.Value2转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!