1

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?

4
  • 2
    Try using .ToString() instead of casting it. Commented Sep 8, 2016 at 11:42
  • str = str +"|"+ (range.Cells[rCnt, cCnt] as Excel.Range).Value2.ToString() Commented Sep 8, 2016 at 11:42
  • use Value2.ToString() Commented Sep 8, 2016 at 11:43
  • Check stackoverflow.com/questions/30231413/… . because Value2 might be null according to that link Commented Sep 8, 2016 at 11:45

2 Answers 2

2
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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.