c#:有没有一种方法可以从数据开始处检索excel中的单元格地址?

时间:2019-04-04 06:23:32

标签: c# winforms excel-interop

我正在尝试将Excel数据从一张纸复制到另一张纸。它的工作正常,但问题是:在源文件中,如果数据没有从A1单元格开始(请考虑下图),在这种情况下,我要复制来自单元格 B5 的数据。这里Some header不是必需的。实际数据从Emp ID单元格开始。

Sample Excel

我尝试过的 是,我可以提供一个textbox来输入单元格地址,然后开始从提供的单元格中复制数据地址。但这引入了手动干预。我要自动化。在这方面的任何帮助表示赞赏。感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

假设有一些基本标准,下面的代码应该可以做到。我假设的标准是:1)如果一行包含任何合并的单元格(例如“ Some Header”),则该行不是起始行。 2)起始单元格将在右侧的单元格及其下方的单元格中包含文本。

private static bool RowIsEmpty(Range range)
{
  foreach (object obj in (object[,])range.Value2)
  {
    if (obj != null && obj.ToString() != "")
    {
      return false;
    }
  }

  return true;
}

private static bool CellIsEmpty(Range cell)
{
  if (cell.Value2 != null && cell.Value2.ToString() != "")
  {
    return false;
  }

  return true;
}

private Tuple<int, int> ExcelFindStartCell()
{
  var excelApp = new Microsoft.Office.Interop.Excel.Application();
  excelApp.Visible = true;

  Workbook workbook = excelApp.Workbooks.Open("test.xlsx");
  Worksheet worksheet = excelApp.ActiveSheet;

  // Go through each row.
  for (int row = 1; row < worksheet.Rows.Count; row++)
  {
    Range range = worksheet.Rows[row];

    // Check if the row is empty.
    if (RowIsEmpty(range))
    {
      continue;
    }

    // Check if the row contains any merged cells, if so we'll assume it's
    // some kind of header and move on.
    object mergedCells = range.MergeCells;
    if (mergedCells == DBNull.Value || (bool)mergedCells)
    {
      continue;
    }

    // Find the first column that contains text in this row.
    for (int col = 1; col < range.Columns.Count; col++)
    {
      Range cell = range.Cells[1, col];

      if (CellIsEmpty(cell))
      {
        continue;
      }

      // Now check if the cell to the right also contains text.
      Range rightCell = worksheet.Cells[row, col + 1];

      if (CellIsEmpty(rightCell))
      {
        // No text in right cell, try the next row.
        break;
      }

      // Now check if cell below also contains text.
      Range bottomCell = worksheet.Cells[row + 1, col];

      if (CellIsEmpty(bottomCell))
      {
        // No text in bottom cell, try the next row.
        break;
      }

      // Success!
      workbook.Close();
      excelApp.Quit();
      return new Tuple<int, int>(row, col);
    }
  }

  // Didn't find anything that matched the criteria.
  workbook.Close();
  excelApp.Quit();
  return null;
}