EPPLUS how to know the format of the Worksheet cell

孤者浪人 提交于 2019-11-29 14:52:40

The short answer is if the data in Excel is formatted as a "proper" date field (its format is set to Date and it does not have the triangle in the cell corner) EPPlus will determine that and automatically convert it to a date in the cell store.

Excel stores this information in the XLSX xml files, e.g. sheet1.xml and styles.xml, which you can see by changing the file extension to .ZIP and opening as a compressed folder. So EPPlus will read XML flags and convert the field values to DateTime automatically. If you want to see its gory detail download the EPPlus source code and look at the function private void SetValueFromXml(XmlTextReader xr, string type, int styleID, int row, int col) in the ExcelWorksheet class.

I created a sheet, added a date value, and copy pasted the value to cell B2 but then set the format to number. I then copied B2 to B3 but made the value in B3 a string by putting an ' in front of the value. Like this:

and when I run this unit test everything passes:

[TestMethod]
public void Date_Number_Test()
{
    //http://stackoverflow.com/questions/28591763/epplus-how-to-know-the-format-of-the-worksheet-cell
    var existingFile = new FileInfo(@"c:\temp\datetest.xlsx");

    using (var package2 = new ExcelPackage(existingFile))
    {
        var ws = package2.Workbook.Worksheets["Sheet1"];

        var cell = ws.Cells["B1"];
        Assert.IsTrue(cell.Value is DateTime);

        cell = ws.Cells["B2"];
        Assert.IsTrue(cell.Value is double);

        cell = ws.Cells["B3"];
        Assert.IsTrue(cell.Value is string);
    }
}

But if you are dealing with a sheet with formatting outside your control then I think your approach is correct in that you will have to determine what the "intent" of the numbers are rather then being able to rely on EPPlus (really excel) is reporting them as.

if you want to know current cell format, why dont you use ExcelNumberFormat class?

var style=oSheet.Cells[i, j].style;
string format=style.Numberformat.Format;

This will give you current cell format, i.e, "YYYY-MM-dddd" , "%#.##", and so on.

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