Home » excel » Writing string, numeric data to Excel via C# works, but Excel does not treat numeric data correctly

Writing string, numeric data to Excel via C# works, but Excel does not treat numeric data correctly

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m getting result sets from Sybase that I return to a C# client.

I use the below function to write the result set data to Excel:

private static void WriteData(Excel.Worksheet worksheet, string cellRef, ref string[,] data)
{
     Excel.Range range = worksheet.get_Range(cellRef, Missing.Value);

     if (data.GetLength(0) != 0)
     {
         range = range.get_Resize(data.GetLength(0), data.GetLength(1));

         range.set_Value(Missing.Value, data);
     }
}

The data gets written correctly.

The issue is that since I’m using string array to write data (which is a mixture of strings and floats), Excel highlights every cell that contains numeric data with the message “Number Stored as Text”.

How do I get rid of this issue?

Many thanks,
Chapax

How to&Answers:

Try the following: replace your array of string by an array of object.

var data = new object[2,2];
data[0, 0] = "A";
data[0, 1] = 1.2;
data[1, 0] = null;
data[1, 1] = "B";

var theRange = theSheet.get_Range("D4", "E5");
theRange.Value2 = data;

If I use this code, equivalent to yours:

var data = new string[2,2];

I get the same symptom as you.
As a side benefit, you don’t have to cast anything to string: you can fill your array with whatever you want to see displayed.

Answer:

Try setting the NumberFormat property on the range object.