如何使用Epplus获取excel中已用行范围的准确计数?

时间:2019-04-30 07:23:02

标签: c# epplus

我正在尝试使用Epplus获取excel中正在使用的总行数,但是我无法获得确切的计数,并且该计数还包含null,我只需要使用的单元格的确切范围。

我正在使用的这些代码行

FileInfo fileinfo = new FileInfo(fileName);
ExcelPackage p = new ExcelPackage(fileinfo);
ExcelWorksheet w = p.Workbook.Worksheets[1];
int Rmax = w.Dimension.End.Row;
int Cmax = w.Dimension.End.Column;
Console.WriteLine(Rmax);
Console.WriteLine(Cmax);

2 个答案:

答案 0 :(得分:1)

   int count = Rmax * Cmax;
   int firstCellValue = 0;
   int lastCellValue = 0;

   for (int row = 1; row <= Rmax; row++) {
    for (int column = 1; column <= Cmax; column++) {
     if (string.IsNullOrEmpty(worksheet.Cells[row, column].GetValue<String>())) {
      count--;
     }
    }
   }

更新

     int rowCount = Rmax;
     int count = Rmax * Cmax;
     string firstCellValue = string.Empty;
     string lastCellValue = string.Empty;

     for (int row = 1; row <= Rmax; row++) {
      bool foundValue = false;
      int leftIndex = 1;
      int rightIndex = Cmax;

      for (int column = 1; column <= Cmax; column++) {
       if (leftIndex == rightIndex) {
        if (!foundValue) {
         rowCount--;
         break;
        }
       }
       if (!string.IsNullOrEmpty(worksheet.Cells[row, column].GetValue < String > ())) {
        foundValue = true;
        firstCellValue = worksheet.Cells[row, column].ToString();
        leftIndex++;
       }
       if (!string.IsNullOrEmpty(worksheet.Cells[row, rightIndex].GetValue < String > ())) {
        foundValue = true;
        lastCellValue = worksheet.Cells[row, rightIndex].ToString();
        rightIndex--;
       }

      }


     }

     Console.WriteLine("firstCellValue" + firstCellValue);
     Console.WriteLine("lastCellValue" + lastCellValue);
     Console.WriteLine("Number of cells" + rowCount);

答案 1 :(得分:0)

您可以从这些行中获取行和列

using (ExcelPackage package = new ExcelPackage(stream))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
    int rowCount = worksheet.Dimension.Rows;
    int colCount = worksheet.Dimension.Columns;
}