Ale*_*x N 5 c# excel gembox-spreadsheet
我正在使用名为 Gembox 的外部组件来创建 Excel 报告。
将 C# 中的 DateTime 属性导出到 Excel 时,该值在 Excel 中显示为数字(例如“-693593”)。所有其他(基本)属性类型均显示为所代表的类型。
在 Excel 中,我希望将 DateTime 显示为正确的日期,在 Gembox 选项中,我找不到将格式设置为日期的选项。
另一种选择是在 Excel 中设置值时使用 .ToString() 转换 DateTime,这会给出所需的结果,但有更好的方法吗?
一些简单的代码示例:
ExcelFile excelFile = new ExcelFile();
ExcelWorksheet excelWorksheet = excelFile.Worksheets.Add("MyWorksheet");
int rownumber = 0;
int columnnumber = 2;
DateTime dateTime = DateTime.Now;
excelWorksheet.Cells[rownumber, columnnumber].Value = dateTime;
Run Code Online (Sandbox Code Playgroud)
输出示例:

设置 Excel 单元格的格式以显示日期时间,就像在 Excel 中一样,
ExcelFile excelFile = new ExcelFile();
ExcelWorksheet excelWorksheet = excelFile.Worksheets.Add("MyWorksheet");
int rownumber = 0;
int columnnumber = 2;
DateTime dateTime = DateTime.Now;
Microsoft.Office.Interop.Excel.Range range = excelWorksheet.Cells[rownumber, columnnumber] as Range;
range.NumberFormat = "dd/MMM/yyyy";
range.Value2 = dateTime;
Run Code Online (Sandbox Code Playgroud)
这会将您的 Excel 单元格设置为日期格式。
在行 range.NumberFormat = "dd/MMM/yyyy"; 您可以提供以下任何格式:
dd/MM/yy // 01/01/01
dd/MMM/yy // 01/Jan/01
ddd/MMM/yyyy // Mon/Jan/2001
ddd dd/MMM/yyyy // Mon 01/Jan/2001
hh:mm:ss // 01:01:01 - 24 hour
hh:mm:ss AM/PM // 01:01:01 pm - 12 hour
the format below is for used by the .Net format only, this will not work with Excel.
HH:mm:ss // 01:01:01 - 24 hour
hh:mm:ss t // 01:01:01 pm - 12 hour
HH:mm:ss.fff // 01:01:01.123 - 24 hour with millisecond
or combination of both date and time;
ddd dd/MMM/yyyy hh:mm:ss
Run Code Online (Sandbox Code Playgroud)