OpenXML how to check if a row is empty in a sheet

ⅰ亾dé卋堺 提交于 2020-02-25 05:28:07

问题


I want to check if a row beside the header row is empty in a spreadsheet. If it's empty, I want to delete the sheet. So far I can only get it to look at cell A2 and check if it empty, but is there a way to check the entire row?

Thanks

private void CheckForEmptyRow(WorkbookPart wbp, string sheetId)
{
   Sheet sheet = wbp.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Id == sheetId);
   WorksheetPart wsp = (WorksheetPart).(wbp.GetPartById(sheetId));
   Cell cell = wsp.Worksheet.Descendants<Cell>().Where(c => c.CellReference == "A2").FirstOrDefault();

   If (cell == null)
   {
       sheet.Remove();
       wbp.DeletePart(wsp);
   }

}

回答1:


You can loop through each row and check if the row is null like this:

private void CheckForEmptyRow(WorkbookPart wbp, string sheetId)
{
   Sheet sheet = wbp.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Id == sheetId);
   WorksheetPart wsp = (WorksheetPart).(wbp.GetPartById(sheetId));
   IEnumerable<SheetData> sheetData = wsp.Worksheet.Elements<SheetData>();
   bool isRowEmpty = false;

   foreach (SheetData SD in sheetData)
   {
      IEnumerable<Row> row = SD.Elements<Row>(); // Get the row IEnumerator

      if (row == null)
      {
          isRowEmpty = true;
          break;
      }
   }

   if (isRowEmpty)
   {
       sheet.Remove();
       wbp.DeletePart(wsp);
   }
}



回答2:


John, trying the row==null did not seem to work for me. For whatever reason the spreadsheets we are trying to parse seems to have hundreds of empty, but not null, rows. It looks like some data was put into there as some point and cleared. I ended up with the code below to return me valid rows. In theory you can just do !row.Elements().Any(ce => ce.DataType != null) on any check

    List<Row> rows = sheetData.Elements<Row>()
     .Where(r => r.Elements<Cell>().Any(ce => ce.DataType != null)
     )
     .ToList()
    ;


来源:https://stackoverflow.com/questions/43530035/openxml-how-to-check-if-a-row-is-empty-in-a-sheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!