Convert Number Stored As Text To Number

喜你入骨 提交于 2020-12-03 03:38:24

问题


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.


回答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());
}




回答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;



回答3:


Have you tried using 'w3.Columns.NumberFormat' instead of 'Cells[].Style.NumberFormat.Format'

Its what I'm using in a couple places in an Excel VSTO app and it works great.



来源:https://stackoverflow.com/questions/42240449/convert-number-stored-as-text-to-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!