Leehbi
Leehbi

Reputation: 779

Reading values from Excel with C# converting double to string

I have the code below to iterate through an Excel file to convert it to a pipe delimited file.

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 = "";

            }

Problem is that when I get to a numerical value I get a runtime error "Can't convert double to string"

Any ideas how I can write a double value from Excel to file using StreamWriter?

Upvotes: 1

Views: 2340

Answers (2)

user2960398
user2960398

Reputation: 383

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

Use this way

Upvotes: 2

Bojan B
Bojan B

Reputation: 2111

Casting a value to string like you are doing in your example, does not convert the value to a String value. Since your value is a double as you say you have to use the ToString() method to get a String representation of that value.

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

Casting vs Converting an object toString, when object really is a string

Upvotes: 2

Related Questions