Convert a number saved as text to a number

I have an Excel workbook that has column C as a number saved as text. What is the C # syntax to convert it to a number? I know 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 should I do in C # to convert a column which is numbers stored as text.

+5
source share
3 answers

Converting cell values ​​to .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

+2
source

I do not understand what kuujinbo does with all this package. It's much easier to do the same as with VB:

 using Excel = Microsoft.Office.Interop.Excel; ... Excel.Range rangeOfValues = ws3.Range("C:C"); rangeOfValues.Cells.NumberFormat = "#0"; rangeOfValues.Value = rangeOfValues.Value; 
+1
source

You tried to use 'W3.Columns.NumberFormat' instead of 'Cell []. Style.NumberFormat.Format '

Its what I use in several places in Excel VSTO works fine.

0
source

Source: https://habr.com/ru/post/1264223/


All Articles