Convert Number Stored As Text To Number

16,883

Solution 1

Converting the cell values to the .NET type works for me:

var values = new List<object[]>()
{ 
    new string[] { "0.001", "1.001", "2.002" }, 
    new string[] { "3.003", "4.004", "5.005" },
    new string[] { "6.006", "7.007", "8.008" }
};

using (var package = new ExcelPackage())
{
    var sheet = package.Workbook.Worksheets.Add("Sheet1");
    sheet.Cells["A1"].LoadFromArrays(values);
    foreach (var cell in sheet.Cells["C:C"])
    {
        cell.Value = Convert.ToDecimal(cell.Value);
    }
    sheet.Cells["C:C"].Style.Numberformat.Format = "#,##0.00";
    File.WriteAllBytes(OUTPUT, package.GetAsByteArray());
}

enter image description here

Solution 2

I don't understand what kuujinbo is doing with all that package stuff. Much simpler to do the same thing you did with VB:

using Excel = Microsoft.Office.Interop.Excel;

...

Excel.Range rangeOfValues = ws3.Range("C:C");
rangeOfValues.Cells.NumberFormat = "#0";
rangeOfValues.Value = rangeOfValues.Value;
Share:
16,883
Yohan Greenburg
Author by

Yohan Greenburg

Updated on June 12, 2022

Comments

  • Yohan Greenburg
    Yohan Greenburg almost 2 years

    I have an Excel workbook that has column C as number stored as text. What is the C# syntax to convert it to number? I know that this VBA will do the job

    Range("C:C").Select
    With Selection
        Selection.NumberFormat = "0.00%"
        .Value = .Value
    End With
    

    And I tried this with C# - but it left the numbers stored as text.

    ExcelWorksheet ws3 = pck.Workbook.Worksheets.Add("New Sheet");
    ws3.Cells["A1"].LoadFromDataTable(tableforme, true);
    ws3.View.FreezePanes(2, 4);
    ws3.Cells["C:C"].Style.Numberformat.Format = "#,##0.00";
    ws3.Cells["C:C"].Style.Numberformat.Format = "0%";
    

    What must I do in C# to convert a column that is numbers stored as text.

  • Admin
    Admin over 4 years
    code is working for small digit value can you suggest how to convert 16 digit from scientific value to text ?