将存储为文本的数字转换为数字 [英] Convert Number Stored As Text To Number

查看:66
本文介绍了将存储为文本的数字转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Excel工作簿,其中C列作为数字存储为文本.将其转换为数字的C#语法是什么?我知道这个VBA可以胜任

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

然后我用C#进行了尝试-但它保留了数字存储为文本的形式.

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%";

我必须在C#中执行什么操作才能转换以数字形式存储为文本的列.

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

推荐答案

将单元格值转换为.NET类型对我有用:

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

这篇关于将存储为文本的数字转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆