c# - 使用 C# 将 double 转换为字符串从 Excel 读取值

标签 c#

我有下面的代码来遍历 Excel 文件以将其转换为竖线分隔文件。

for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    str = str +"|"+ (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;

                }
                sw.WriteLine(str);
                str = "";

            }

问题是,当我得到一个数值时,我得到一个运行时错误“无法将 double 转换为字符串”

关于如何使用 StreamWriter 将 double 值从 Excel 写入文件有什么想法吗?

最佳答案

public static string ToStr(object readField)
{
    if ((readField != null))
    {
        if (readField.GetType() != typeof(System.DBNull))
        {
            return Convert.ToString(readField);
        }
        else
        {
            return "";
        }
    }
    else
    {
        return "";
    }
}

str = str +"|"+ ToStr((range.Cells[rCnt, cCnt] as Excel.Range).Value2);

这样使用

关于c# - 使用 C# 将 double 转换为字符串从 Excel 读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39389968/

相关文章:

c# - 需要参数的对象的依赖注入(inject)

c# - 为什么以下代码片段会成为 C#2.0 类型推断的问题?

c# - 从一个 DataTable 中选择行而不是另一个

c# - Xunit 报告工具

c# - 为什么从 <T> 到 <U> 的隐式转换运算符接受 <T?>?

c#表达式和循环之美

c# - 单声道/WCF : Cannot determine caller IP on Ubuntu

c# - 在 C# 中卸载时,如何检查 <service>.exe 上的锁是否已释放?

C# ASP.NET HttpWebRequest 自动解码查询字符串中的符号 (&) 值?

c# - EmbeddedConfiguration 中的 UniqueConstraint