如何在日期列中将单元格留空而不是在 EPPlus 中写入 DateTime.Min

How to leave cells empty in Date column instead of writing DateTime.Min in EPPlus

我需要使用 EPPlus 将格式化日期写入 Excel,在没有日期可写的地方留下空白单元格。我尝试了以下方法:

  1. 正在写入日期,然后对其进行格式化。这有效,除非我没有日期,在这种情况下,最小值被写入:

  1. 将日期格式化为字符串(没有日期时传递空字符串),然后指定自定义格式。 The problem with this is that Excel doesn't see the type as a date,因此下游系统无法使用它:

如何使用 EPPlus 将日期写入 Excel,其中日期被识别为日期类型(而非字符串),但根本不写入缺少的日期值?

确保您绑定到日期列的数据是 DateTime? 类型(可为空)。 仅当您提供 null 值时,才会呈现一个空列。

例如:

// Date format on first column
sheet.Column(1).Style.Numberformat.Format = "yyyy-mm-dd";

// Some date values
var columnValues = new List<DateTime?> {
    DateTime.Now,
    null,
    DateTime.Now.AddDays(1) };

// Bind values to column
sheet.Cells[1, 1].LoadFromArrays(columnValues.Select(v => new object[] { v }));

结果: