How To Set Cell Data Type

做~自己de王妃 提交于 2021-01-21 04:03:29

问题


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?


回答1:


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();
    }
}



回答2:


Here are the 49 formats listed in EPPlus/EPPlus/Style/ExcelNumberFormat.cs (located here):

"General"
"0"
"0.00"
"#,##0"
"#,##0.00"
"0%"
"0.00%"
"0.00E+00"
"# ?/?"
"# ??/??"
"mm-dd-yy"
"d-mmm-yy"
"d-mmm"
"mmm-yy"
"h:mm AM/PM"
"h:mm:ss AM/PM"
"h:mm"
"h:mm:ss"
"m/d/yy h:mm"
"#,##0 ;(#,##0)"
"#,##0 ;[Red](#,##0)"
"#,##0.00;(#,##0.00)"
"#,##0.00;[Red](#,#)"
"mm:ss"
"[h]:mm:ss"
"mmss.0"
"##0.0"
"@"



回答3:


This advice is great, for setting number cell type in Excel I used

worksheet.Column(1).Style.Numberformat.Format = "#,##0.000";

but I would really like to find some table of formats in EPPlus and cell types in Excel to get another Excel types like Currency, Percentage etc...



来源:https://stackoverflow.com/questions/29473920/how-to-set-cell-data-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!