How To Set Cell Data Type

前端 未结 3 1150
庸人自扰
庸人自扰 2021-02-14 14:24

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

3条回答
  •  鱼传尺愫
    2021-02-14 15:19

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

提交回复
热议问题