Reading dates from OpenXml Excel files

前端 未结 4 1233
孤独总比滥情好
孤独总比滥情好 2020-12-28 10:25

I\'m trying to read data from the .xlsx files using SharpZipLib to unpack it (in memory) and reading the inner xml files. Everything is fine but recognizing the dates - they

4条回答
  •  佛祖请我去吃肉
    2020-12-28 10:51

    Cells may have styles. These are uints that index cellXfs in the styleSheet. Each cellXfs item contains a set of attributes. The most important is NumberFormatID. If its value falls in the range 14-22 it is a "standard" date. If it falls in the range 165 - 180, it is a "formatted" date and will have a corresponding NumberingFormat attribute.

    Standard Date

    [x:c r="A2" s="2"][x:v]38046[/x:v][/x:c]

    [x:xf numFmtId="14" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1" /] (ordinal position 2)

    Formatted Date

    [x:c r="A4" s="4"][x:v]38048[/x:v][/x:c]

    [x:xf numFmtId="166" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1" /](ordinal position 4)

    [x:numFmt numFmtId="166" formatCode="m/d;@" /]

    This code extracts a list of style IDs that correspond to these date formats.

      private void GetDateStyles()
      {
         //
         // The only way to tell dates from numbers is by looking at the style index. 
         // This indexes cellXfs, which contains NumberFormatIds, which index NumberingFormats.
         // This method creates a list of the style indexes that pertain to dates.
         WorkbookStylesPart workbookStylesPart = (WorkbookStylesPart) UriPartDictionary["/xl/styles.xml"];
         Stylesheet styleSheet = workbookStylesPart.Stylesheet;
         CellFormats  cellFormats = styleSheet.CellFormats;
    
         int i = 0;
         foreach (CellFormat cellFormat in cellFormats)
         {
            uint numberFormatId = cellFormat.NumberFormatId;
            if ((numberFormatId >= 14 && numberFormatId <= 22) 
            || (numberFormatId >= 165u && numberFormatId <= 180u))
            {
               _DateStyles.Add(i.ToString());
            }
            i++;
         }
    

提交回复
热议问题