将存储为文本的数字转换为数字

时间:2017-02-15 03:56:37

标签: c# excel c#-4.0 vsto epplus

我有一个Excel工作簿,其中C列作为文本存储。将它转换为数字的C#语法是什么?我知道这个VBA将完成这项工作

image = shopify.Image.find(variant.image_id)
image_url = image.scr

我用C#尝试了这个 - 但它将数字存储为文本。

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

我必须在C#中做什么来转换作为文本存储的数字的列。

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

我不明白kuujinbo正在做什么包装的东西。 使用VB做同样的事情要简单得多:

using Excel = Microsoft.Office.Interop.Excel;

...

Excel.Range rangeOfValues = ws3.Range("C:C");
rangeOfValues.Cells.NumberFormat = "#0";
rangeOfValues.Value = rangeOfValues.Value;

答案 2 :(得分:0)

你试过用过吗?     'w3.Columns.NumberFormat' 代替     '细胞[]。Style.NumberFormat.Format'

我在Excel VSTO应用程序中的几个地方使用它并且效果很好。