I am trying to set data type of cell, but it seems that's impossible to do with EPPlus.
If I place a number as value in cell, I get General data type in exported Excel file.
If set NumberFormat of Cells, for example:
workSheet.Cells[range].Style.Numberformat.Format = "mm/dd/yyyy hh:mm:ss";
Then I still will not get Date or Time. Exported Excel file will show cells as Custom data type.
I can get General or Custom data types only. I want to set Cells' data type to Time, but I can't. The problem is, if data type is not set, then for some reason Pivot table in other sheet is sorting numbers as strings :(
So, is there any way to set data type of cell please?
The number formatting gets a little weird with excel. Basically, it is a list of predefined strings so it does a match cell by cell. To see what that list looks like in EPPlus check out the ExcelNumberFormat.cs class in the source code.
But if you just need to have Excel "see" the cell as a certain type in the Number -> Number Format dropdown in the HOME ribbon, this should get you it:
[TestMethod]
public void Date_Format_Test()
{
//http://stackoverflow.com/questions/29473920/how-to-set-cell-data-type
var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var pck = new ExcelPackage(existingFile))
{
var ws = pck.Workbook.Worksheets.Add("Content");
var date = DateTime.Now;
//Raw date value as number
ws.Cells["A1"].Value = date;
//As "Short Date"
ws.Cells["A2"].Value = date;
ws.Cells["A2"].Style.Numberformat.Format = "mm-dd-yy";
//As "Time"
ws.Cells["A3"].Value = date;
ws.Cells["A3"].Style.Numberformat.Format = "[$-F400]h:mm:ss\\ AM/PM";
pck.Save();
}
}