6

ClosedXml does not allow to insert minimum datetime into cell. My datatable includes minimum datetime values that ClosedXml does not like.

using (var workbook = new XLWorkbook())
{
    var dataTable = GetDataTable();
    workbook.Worksheets.Add(dataTable, "myWorksheet"); // Exception thrown
    workbook.SaveAs(filePath);
}

Exception is thrown when adding a worksheet: 'Unable to set cell value to 01/01/0001 00:00:00'

How could I allow ClosedXml to insert this value without throwing exception? For example it could write empty values instead of throwing exception. Would it be possible to get around this without modifying the dataTable to clean up these minimum datetime values?

Pegaz
  • 367
  • 2
  • 12

4 Answers4

6

Excel itself doesn't allow you to set a cell value to such a low date value. Try it for yourself. Previously, one could set the value in ClosedXML, but Excel would then believe that the file is corrupt. The check was added to avoid the creation of a seemingly corrupt file.

Raidri
  • 17,258
  • 9
  • 62
  • 65
Francois Botha
  • 4,520
  • 1
  • 34
  • 46
0

Try to change your DateTime default value to UTC:

DateTime dt = new DateTime();
dt.ToUniversalTime()   
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
marcolomew
  • 11
  • 2
  • I've wrote this comment because utc is defined as: It is the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970 (value allowed on excel) – marcolomew Jul 08 '19 at 15:35
0

I have the same situation here. the solution is simple, to have the datatable field datetime with null value so ClosedXML can proses the null date and change it to empty

0

As others have mentioned, Excel will not allow dates before January 1st 1970 December 30th 1899.

I just wanted to add that you can use DateTime.UnixEpoch instead of DateTime.MinValue as your minimum date time. DateTime.UnixEpoch is defined as DaysTo1970 * TicksPerDay.

The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 1970, in the Gregorian calendar.

Edit: Corrected minimum date, thx breeze. Personally I would still use DateTime.UnixEpoch as a minimum date, as it looks less specific, but whatever floats your boat.

  • 1
    I think this information is incorrect. The minimum date that excel supports is 1899-12-30 according to this issue: https://github.com/ClosedXML/ClosedXML/issues/1163#issuecomment-476294478 I can confirm that I'm able to enter dates bigger or equal to January 1st 1900 as Excel automatically converts those to a readable format. – brz Sep 29 '22 at 13:42