打开xml sdk读取Number和datetime / number值

时间:2013-02-25 11:49:07

标签: c# excel openxml-sdk

我正在使用Open XML SDK 2.0来读取excel文件。该文件包含如下信息。

Number DataFound摘要

10 2012-12-12 abslsoddsdls

20 2012-11-12 sllsdislkdrr

当我使用Open XML SDK从文件中获取数据时,我总是将单元格DataType作为String(sharedstring)获取..我需要获取excel文件中的数据类型。看看下面的代码。任何想法我怎样才能获得excel文件中单元格的数据类型?

 SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(dataStream, false);
            WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
            IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
            string relationshipId = sheets.First().Id.Value;
            WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
            Worksheet workSheet = worksheetPart.Worksheet;
            SheetData sheetData = workSheet.GetFirstChild<SheetData>();
            IEnumerable<Row> rows = sheetData.Descendants<Row>();
            foreach (Cell cell in rows.ElementAt(0))
            {
                dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
            }

            foreach (Row row in rows) //this will also include your header row...
            {
                DataRow tempRow = dt.NewRow();

                for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                {
                    tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i ));
                }

                dt.Rows.Add(tempRow);
            }
            dt.Rows.RemoveAt(0);



public static string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
  SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            string value = cell.CellValue.InnerXml;

            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString) //cell.DataType is always SharedString!
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else
            {
                return value;
            }
        }

0 个答案:

没有答案