Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Excel Cell Value From Text To Number Using C#

Tags:

c#

excel

I am using Windows Application. In that Application i exported the DataGrid into Excel Successfully... Now the problem is , When i exported from Grid to the Excel Sheet, The cell values are having some green color mark on left top corner in the Excel Sheet... I thought that is type cast problem . How Shall i avoid that Problem.... and How to change the cell value from text to Number ...(i.e)Convert To Number....

Can Anyone tell me the solution of this problem?

My Code for Formatting That Excel Sheet For Some Range of Values,

wksheet.Range[GetRanges[0].ToString(), GetRanges[GetRanges.Count-2].ToString()].Merge();

wksheet.get_Range(GetRanges[0].ToString(), GetRanges[GetRanges.Count-].ToString()).Interior.Color = Color.FromArgb(192, 0, 0);
                         
like image 518
Suryakavitha Avatar asked Sep 30 '10 07:09

Suryakavitha


People also ask

How do I extract numbers from text in Excel?

Select all cells with the source strings. On the Extract tool's pane, select the Extract numbers radio button. Depending on whether you want the results to be formulas or values, select the Insert as formula box or leave it unselected (default).


2 Answers

I haven't a Windows machine to test on at the moment, but perhaps you would want to try changing the cell format, e.g.:

my_range.NumberFormat = "0.0"; // change number of decimal places as needed

Here's a full example from Microsoft: How to automate Microsoft Excel from Microsoft Visual C#.NET.

like image 157
mechanical_meat Avatar answered Oct 09 '22 21:10

mechanical_meat


The following routine will dynamically fill a spreadsheet from data (text and numbers) in a text file.

The kicker is using an object array to set the values.

StreamReader STRead;
String[] STCells;
object[] cellData;
int temp;
Excel.Range tempRange;
for (int i = 0; i < FileList.Length; i++)
{
    STRead = FileList[i].OpenText();
    int j = 0;
    while (!STRead.EndOfStream)
    {
        STCells = STRead.ReadLine().Split(',');
        cellData = new object[STCells.Length];
        for (int k = 0; k < STCells.Length; k++)
        {
            if (Int32.TryParse(STCells[k], out temp)) 
                cellData[k] = temp;
            else
                cellData[k] = STCells[k];
        }
        tempRange = sheetList[i].get_Range(ReturnCellID(j, 0), 
                                           ReturnCellID(j, STCells.Length - 1));
        j++;
        tempRange.Value2 = cellData;
    }
    STRead.Close();
}
like image 36
Nick Neander Avatar answered Oct 09 '22 21:10

Nick Neander