数字格式使指能够控制Excel单元格中数字如何显示的格式字符串。例如,我们可以对数字12345应用数字格式“0.00”,使之显示为“12345.00”。在例如对数字12345应用“¥0.00”格式,使之显示为“¥12345.00”。数字格式字符串通常由以下某个或某几个说明符构成:
- # :数字占位符
- 0 :0占位符
- . :小数点
- , :分组符
- % :百分号占位符
- [Red] :颜色说明符
更多格式说明符,请参阅:【微软】自定义数字格式字符串
本文将展示如何使用Spire.XLS (Excel类库),通过C#代码在Excel工作表中为数字添加格式。下载该类库,添加DLL文件为引用,并在程序开头添加以下命名空间。
using Spire.Xls;
使用代码:
//初始化Workbook对象
Workbook workbook = new Workbook();
//获取第一个工作表
Worksheet sheet = workbook.Worksheets[0];
//写入文本到B1,C1
sheet.Range["B1"].Text = "数字格式";
sheet.Range["C1"].Text = "数字±12345678应用格式后的效果";
sheet.Range["B1"].Style.Font.IsBold = true;
sheet.Range["C1"].Style.Font.IsBold = true;
//在B3中写入文本(即数字格式),在C3中写数字并应用数字格式
sheet.Range["B3"].Text = "0";
sheet.Range["C3"].NumberValue = 12345678;
sheet.Range["C3"].NumberFormat = "0";
//重复上面的步骤写入更多格式及对应效果
sheet.Range["B4"].Text = "0.00";
sheet.Range["C4"].NumberValue = 12345678;
sheet.Range["C4"].NumberFormat = "0.00";
sheet.Range["B5"].Text = "#,##0.00";
sheet.Range["C5"].NumberValue = 12345678;
sheet.Range["C5"].NumberFormat = "#,##0.00";
sheet.Range["B6"].Text = "¥#,##0.00";
sheet.Range["C6"].NumberValue = 12345678;
sheet.Range["C6"].NumberFormat = "¥#,##0.00";
sheet.Range["B7"].Text = "0;[Red]-0";
sheet.Range["C7"].NumberValue = -12345678;
sheet.Range["C7"].NumberFormat = "0;[Red]-0";
sheet.Range["B8"].Text = "0.00;[Red]-0.00";
sheet.Range["C8"].NumberValue = -12345678;
sheet.Range["C8"].NumberFormat = "0.00;[Red]-0.00";
sheet.Range["B9"].Text = "#,##0;[Red]-#,##0";
sheet.Range["C9"].NumberValue = -12345678;
sheet.Range["C9"].NumberFormat = "#,##0;[Red]-#,##0";
sheet.Range["B10"].Text = "#,##0.00;[Red]-#,##0.000";
sheet.Range["C10"].NumberValue = -12345678;
sheet.Range["C10"].NumberFormat = "#,##0.00;[Red]-#,##0.00";
sheet.Range["B11"].Text = "0.00E+00";
sheet.Range["C11"].NumberValue = 12345678;
sheet.Range["C11"].NumberFormat = "0.00E+00";
sheet.Range["B12"].Text = "0.00%";
sheet.Range["C12"].NumberValue = 12345678;
sheet.Range["C12"].NumberFormat = "0.00%";
//设置[B3:B12]、[C3:C12]背景颜色
sheet.Range["B3:B12"].Style.KnownColor = ExcelColors.Gray25Percent;
sheet.Range["C3:C12"].Style.KnownColor = ExcelColors.Gray50Percent;
//设置2、3列列宽
sheet.Columns[1].ColumnWidth = 25;
sheet.Columns[2].ColumnWidth = 30;
//保存文档
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013);