tags:

views:

323

answers:

2

Hi, 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

A: 

Try setting the NumberFormat property on the range object.

Timores
I will try this ... but have a concern -- there is a mixture of Strings and numeric in this String array
Chapax
You can attempt to cast each item to `float` or `decimal` or whatever within a `try...catch` block -- if it works, set the `NumberFormat` for the cell range accordingly.
Jay
+1  A: 

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.

Mathias
did not work ...
Chapax
did you pass the numbers as float in your array?
Mathias
if the array you receive is an array of strings, then Excel will format it as strings. If it's an array of objects and some are numbers, Excel should recognize it. But if your array of objects contains strings, some of them happening to be numbers, they will still be formatted as strings. Note that in my example data[0,1] receives a double, not a string.If you can't directly get an array of objects of the correct type, you may have to re-cast the contents of your array, so that the cells that can/should be doubles is casted to double.
Mathias
Worked perfectly Mathias.Yes, I was passing in an array of Strings to populate the 2D array.Earlier I was just explicitly casting this array to 'object', but now have written a different method to obtain only objects.Many thanks for your help.
Chapax
Glad it helped. You seem to believe this answer was the correct one, maybe you can accept it as such?
Mathias