Ho utilizzato il codice fornito da Andrew J, ma il DataType CellValues.Date ha prodotto un file xlsx danneggiato per me.
il tipo di dati CellValues.Number funzionato bene per me (Non dimenticare di impostare NumberFormatId):
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
Tutto il mio codice:
DateTime valueDate = DateTime.Now;
string valueString = valueDate.ToOADate().ToString();
CellValue cellValue = new CellValue(valueString);
Cell cell = new Cell();
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.StyleIndex = yourStyle; //StyleIndex of CellFormat cfBaseDate -> See below
cell.Append(cellValue);
mio CellFormat per questa cella nel foglio di stile:
CellFormat cfBaseDate = new CellFormat() {
ApplyNumberFormat = true,
NumberFormatId = 14, //14 is a localized short Date (d/m/yyyy) -> See list below
//Some further styling parameters
};
Se vuoi formattare la data di un altro modo, ecco un elenco di tutti i predefinito Excel di NumberFormatId
ID FORMAT CODE
0 General
1 0
2 0.00
3 #,##0
4 #,##0.00
9 0%
10 0.00%
11 0.00E+00
12 # ?/?
13 # ??/??
14 d/m/yyyy
15 d-mmm-yy
16 d-mmm
17 mmm-yy
18 h:mm tt
19 h:mm:ss tt
20 H:mm
21 H:mm:ss
22 m/d/yyyy H:mm
37 #,##0 ;(#,##0)
38 #,##0 ;[Red](#,##0)
39 #,##0.00;(#,##0.00)
40 #,##0.00;[Red](#,##0.00)
45 mm:ss
46 [h]:mm:ss
47 mmss.0
48 ##0.0E+0
49 @
Fonte della lista: http://closedxml.codeplex.com/wikipage?title=NumberFormatId%20Lookup%20Table
So che questo elenco è da ClosedXML, ma è lo stesso in OpenXML.
E fare attenzione alla bandiera del 1904: le date possono essere impostate tra 1-1-1900 o 1-1-1904 (a causa di un bug nel modo in cui calcola gli anni bisestili). –
Questa soluzione ha funzionato per me, grazie – Selwyn
Stranamente non ha funzionato per me. Anche su Excel 2010. (CellValues.Date non dovrebbe essere supportato nel 2007) – GaussZ