简体   繁体   English

C#擅长如何在使用范围内查找第一个单元格。

[英]c# excel how to Find First Cell in a used range.

I can use XlCellType.xlCellTypeLastCell to find last cell in the used range. 我可以使用XlCellType.xlCellTypeLastCell来找到使用范围内的最后一个单元格。 How to get first cell in one line ? 如何在一行中获得第一个单元格?

Code to get last cell position. 代码以获取最后一个单元格位置。

    Excel.Range mergeCells = (Excel.Range)mergeSheet.Cells[6,1].EntireRow;
    var rowRng = mergeCells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
    var colPosition = rowRng.Column;

One way is to get mergeCells.value and loop through to increment a counter until I see null/empty value. 一种方法是获取mergeCells.value并循环循环以增加计数器,直到看到空值/空值。 But I was hoping to get this in one line. 但是我希望能做到这一点。 Any ideas ? 有任何想法吗 ?

Test Cases: 测试用例:

(1) (1)

在此处输入图片说明

Expected Result colPosition = 1 预期结果colPosition = 1

(2) (2) 在此处输入图片说明

Expected Result colPosition = 5 预期结果colPosition = 5

Here is a solution using the Excel Interop library (as tagged in the question). 这是使用Excel Interop库的解决方案(如问题中所标记)。 The below method will return a 1-based column index of the first cell in a given row. 下面的方法将返回给定行中第一个单元格的从1开始的列索引。 It worked for me on your supplied test cases as well as a few of my own. 它适用于您提供的测试用例以及我自己的一些用例。 Note that if you wish to simply use the first row in the used range - rather than a supplied row, you can find the first used row number using ActiveSheet.UsedRange.Rows[1].Row . 请注意,如果您只想使用已使用范围中的第一行-而不是提供的行,则可以使用ActiveSheet.UsedRange.Rows[1].Row查找第一个已使用的行号。

    public static int FindFirstCellInExcelRow(string filePath, int rowNum)
    {
        Excel.Application xlApp = null;
        Excel.Workbook wkBook = null;
        Excel.Worksheet wkSheet = null;
        Excel.Range range = null;
        try
        {
            xlApp = new Excel.Application();
            wkBook = xlApp.Workbooks.Open(filePath);
            wkSheet = wkBook.ActiveSheet;
            range = wkSheet.Cells[rowNum, 1].EntireRow;
            if (range.Cells[1, 1].Value != null)
            {
                return range.Cells[1, 1].Column;
            }
            var result = range.Find(What: "*", After: range.Cells[1, 1], LookAt: Excel.XlLookAt.xlPart, LookIn: Excel.XlFindLookIn.xlValues, SearchOrder: Excel.XlSearchOrder.xlByColumns, SearchDirection: Excel.XlSearchDirection.xlNext, MatchByte: false, MatchCase: false);
            int colIdx = result?.Column ?? 0; // return 0 if no cell in row contains value
            return colIdx;
        }
        finally
        {
            wkBook.Close();
            Marshal.ReleaseComObject(xlApp);
            Marshal.ReleaseComObject(wkBook);
            Marshal.ReleaseComObject(wkSheet);
            Marshal.ReleaseComObject(range);
            xlApp = null;
            wkBook = null;
            wkSheet = null;
            range = null;
        }
    }

I highly (x10) recommend using ClosedXML over Microsoft's Excel libraries (unless you are using the old xls files). 我强烈(x10)建议在Microsoft的Excel库上使用ClosedXML(除非您使用的是旧的xls文件)。 Using ClosedXML you would do the following (this is taken right from their webpage): 使用ClosedXML,您将执行以下操作(此操作直接从他们的网页上进行):

Get it right off the NuGet packages. 立即从NuGet软件包中获取它。 Install-Package ClosedXML -Version 0.93.1

https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data

  var wb = new XLWorkbook(northwinddataXlsx);
  var ws = wb.Worksheet("Data");

  // Look for the first row used
  var firstRowUsed = ws.FirstRowUsed();

  // Narrow down the row so that it only includes the used part
  var categoryRow = firstRowUsed.RowUsed();

  // Move to the next row (it now has the titles)
  categoryRow = categoryRow.RowBelow();

  // Get all categories
  while (!categoryRow.Cell(coCategoryId).IsEmpty())
  {
    String categoryName = categoryRow.Cell(coCategoryName).GetString();
    categories.Add(categoryName);

    categoryRow = categoryRow.RowBelow();
  }

try the below code snippet, this will give the first row of a excel used range 尝试下面的代码片段,这将给出excel使用范围的第一行

Excel.Workbook xlWB = Globals.ThisAddIn.Application.ActiveWorkbook;
Excel.Worksheet xlWS = xlWB.ActiveSheet;
int firstRow = xlWS.UsedRange.Row;

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

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