简体   繁体   English

使用Open XML SDK C#阅读Excel

[英]Reading excel using Open XML SDK c#

I am trying to read excel using Open XML SDK in C# using Visual Studio 2013. I followed the following links http://msdn.microsoft.com/en-us/library/office/hh298534(v=office.15).aspx http://msdn.microsoft.com/en-us/library/office/gg575571.aspx 我正在尝试使用Visual Studio 2013在C#中使用Open XML SDK读取excel。我遵循以下链接http://msdn.microsoft.com/zh-cn/library/office/hh298534(v=office.15).aspx http://msdn.microsoft.com/zh-CN/library/office/gg575571.aspx

The code is 该代码是

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();
     }
    }
   }
 }

I tried the following code also 我也尝试了以下代码

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;
       }
      }
   }
}                  
}
}
}

But both are returning only numeric values, not text. 但是两者都只返回数字值,而不返回文本。 Can anyone please help on how to read excel text using Open XML SDK in C#.? 谁能帮忙使用C#中的Open XML SDK读取Excel文本吗?

I have not used to OpenXML SDK directly, but have you tried used ClosedXML ? 我还没有直接使用过OpenXML SDK,但是您尝试过使用ClosedXML吗? It's a wrapper around the SDK that makes reading and writing Excel documents a breeze. 它是SDK的包装,使阅读和编写Excel文档变得轻而易举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM