16

I have date's in an excel sheet that I am reading from. What I like to do is to force the date to be in mm/dd/yyyy Is there a way to do this in Closed XML.

I took at a look https://closedxml.codeplex.com/documentation but could not find how to force or update the date to a certain format.

Nate Pet
  • 44,246
  • 124
  • 269
  • 414

3 Answers3

22

If you want to do it on Specific cell then you have to use

worksheet.Cell(row,column).Style.NumberFormat.Format = "mm/dd/yyyy";

and

If you want to do it on multiple cells then you have to use

worksheet.Range(row,column,row,column).Style.NumberFormat.Format = "mm/dd/yyyy";
Smit Patel
  • 2,992
  • 1
  • 26
  • 44
1

Cell value should come as a datetime datatype. Specific cells or between the range.

Style.DateFormat or Style.NumberFormat both will works. Use the below code:

ws.Range(firstCellAddress,lastCellAddress).SetDataType(XLDataType.DateTime);
ws.Range(firstCellAddress,lastCellAddress).Style.DateFormat.Format = "mm/dd/yyyy"; // "dd/mm/yyyy" or whatever format needed"

ws.Range("A","C").SetDataType(XLDataType.DateTime);
ws.Range("A","C").Style.DateFormat.Format = "mm/dd/yyyy";

or

ws.Range(rangeAddress).SetDataType(XLDataType.DateTime);
ws.Range(rangeAddress).Style.DateFormat.Format = "mm/dd/yyyy";

ws.Range("A:D").SetDataType(XLDataType.DateTime);
ws.Range("A:D").Style.DateFormat.Format = "mm/dd/yyyy";
Sathish
  • 49
  • 3
0

I know the question has already been aswered... but since I still lost some hours after reading this, i'd like to leave this for my future me:

Make sure you are not clearing all formats after setting the cell format. I had this code at the bottom of the method...

var range = worksheet.Range(firstCell.Address, lastCell.Address);
range.Clear(XLClearOptions.AllFormats);
Nahue Gonzalez
  • 273
  • 4
  • 10