c# – 如何计算OpenXML中每个工作表的行数

前端之家收集整理的这篇文章主要介绍了c# – 如何计算OpenXML中每个工作表的行数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从Interop库切换到Open XML,因为我需要读取大型Excel文件.在此之前,我可以使用:
worksheet.UsedRange.Rows.Count

获取工作表上包含数据的行数.我使用这些信息来制作进度条.在OpenXML中,我不知道如何获得有关工作表的相同信息.我现在拥有的是这段代码

using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(path,false))
{
    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
    int row_count = 0,col_count;
    // here I would like to get the info about the number of rows
    foreach (Row r in sheetData.Elements<Row>())
    {
        col_count = 0;
        if (row_count > 10)
        {
            foreach (Cell c in r.Elements<Cell>())
            {
                // do some stuff  
                // update progressbar  
            }
        }
        row_count++;
    }
}

解决方法

这并不难(当你使用LINQ时),
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open("PATH",true))
 {
   //Get workbookpart
   WorkbookPart workbookPart = myDoc.WorkbookPart;

   //then access to the worksheet part
   IEnumerable<WorksheetPart> worksheetPart = workbookPart.WorksheetParts;

   foreach (WorksheetPart WSP in worksheetPart)
   {
      //find sheet data
      IEnumerable<SheetData> sheetData = WSP.Worksheet.Elements<SheetData>();       
      // Iterate through every sheet inside Excel sheet
      foreach (SheetData SD in sheetData)
      {
           IEnumerable<Row> row = SD.Elements<Row>(); // Get the row IEnumerator
           Console.WriteLine(row.Count()); // Will give you the count of rows
      }
}

编辑Linq现在直截了当.

原文链接:https://www.f2er.com/csharp/243839.html

猜你在找的C#相关文章