EPPLUS how to know the format of the Worksheet cell

前端 未结 2 1308
[愿得一人]
[愿得一人] 2021-01-21 16:00

I am using EPPlus to read excel sheets and load the data into datatable to perform further operations and then save back the modified data to the excel file.

The below c

相关标签:
2条回答
  • 2021-01-21 16:20

    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-ffffdd" , "%#.##", and so on.

    0 讨论(0)
  • 2021-01-21 16:23

    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:

    enter image description here

    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.

    0 讨论(0)
提交回复
热议问题