使用Open XML SDK c#读取excel

时间:2014-12-24 07:29:34

标签: c# visual-studio-2013 openxml-sdk

我正在尝试使用Visual Studio 2013在C#中使用Open XML SDK读取excel。 我按照以下链接 http://msdn.microsoft.com/en-us/library/office/hh298534(v=office.15).aspx http://msdn.microsoft.com/en-us/library/office/gg575571.aspx

代码是

using (SpreadsheetDocument document = SpreadsheetDocument.Open(excelPath, true))
{
  WorkbookPart workbookPart = document.WorkbookPart;
  foreach (WorksheetPart workSheetPart in workbookPart.WorksheetParts)
  {
   SheetData sheetData = workSheetPart.Worksheet.Elements<SheetData>().First();
   IEnumerable<Row> rows = sheetData.Elements<Row>().Where(x => x.RowIndex > 1);
   foreach (Row r in rows)
    {
     IEnumerable<string> textValues = from cell in r.Descendants<Cell>() where cell.CellValue != null select cell.CellValue.Text;
     foreach (var cell in textValues)
     {
     string str = cell.ToString();
     }
    }
   }
 }

我也试过以下代码

using (SpreadsheetDocument document = SpreadsheetDocument.Open(excelPath, true))
{
 WorkbookPart workbookPart = document.WorkbookPart;
 foreach (WorksheetPart workSheetPart in workbookPart.WorksheetParts)
  {
   SheetData sheetData = workSheetPart.Worksheet.Elements<SheetData>().First();
   IEnumerable<Row> rows = sheetData.Elements<Row>().Where(x => x.RowIndex > 1);
   foreach (Row r in rows)
   {
    List<Cell> cells = r.Descendants<Cell>().ToList();
    foreach (var cell in cells)
    {
     if (cell != null)
     {
     string value = cell.CellValue.Text;
     if (cell.DataType != null)
     {
     switch (cell.DataType.Value)
      {
      case CellValues.SharedString:
        var stringTable = workSheetPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
        if (stringTable != null)
        {
         value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
         }
         break;
       }
      }
   }
}                  
}
}
}

但两者都只返回数值,而不是文本。任何人都可以请教如何使用C#中的Open XML SDK阅读excel文本。?

1 个答案:

答案 0 :(得分:0)

我还没有直接使用过OpenXML SDK,但您是否尝试过使用ClosedXML?它是SDK的一个包装器,使得读取和编写Excel文档变得轻而易举。