如何使用ClosedXML用数字格式化单元格?

时间:2019-03-15 05:59:37

标签: c# excel export closedxml

通过使用以下代码,我仅格式化相应的单元格,但是当我选择整列时,其将常规格式显示为标签,请参见附件图片enter image description here enter image description here

var ws = wb.Worksheets.Add("Contacts");

//Adding text
//Title
ws.Cell("B2").Value = "Contacts";
//First Names
ws.Cell("B3").Value = "FName";
ws.Cell("B4").Value = "John";
ws.Cell("B5").Value = "Hank";
ws.Cell("B6").SetValue("Dagny"); // Another way to set the value

//Last Names
ws.Cell("C3").Value = "LName";
ws.Cell("C4").Value = "Galt";
ws.Cell("C5").Value = "Rearden";
ws.Cell("C6").SetValue("Taggart"); // Another way to set the value

//Adding more data types
//Is an outcast?
ws.Cell("D3").Value = "Outcast";
ws.Cell("D4").Value = true;
ws.Cell("D5").Value = false;
ws.Cell("D6").SetValue(false); // Another way to set the value

//Date of Birth
ws.Cell("E3").Value = "DOB";
ws.Cell("E4").Value = new DateTime(1919, 1, 21);
ws.Cell("E5").Value = new DateTime(1907, 3, 4);
ws.Cell("E6").SetValue(new DateTime(1921, 12, 15)); // Another way to set the value

//Income
ws.Cell("F3").Value = "Income";
ws.Cell("F4").Value = 2000;
ws.Cell("F5").Value = 40000;
ws.Cell("F6").SetValue(10000); // Another way to set the value

//Defining ranges
//From worksheet
var rngTable = ws.Range("B2:F6");

//From another range
var rngDates = rngTable.Range("D3:D5"); // The address is relative to rngTable (NOT the worksheet)
var rngNumbers = rngTable.Range("E3:E5"); // The address is relative to rngTable (NOT the worksheet)

//Formatting dates and numbers
//Using a OpenXML's predefined formats
rngDates.Style.NumberFormat.NumberFormatId = 15;

//Using a custom format
rngNumbers.Style.NumberFormat.Format = "$ #,##0";

0 个答案:

没有答案
相关问题