简体   繁体   中英

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

I can use XlCellType.xlCellTypeLastCell to find last cell in the used range. 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. But I was hoping to get this in one line. Any ideas ?

Test Cases:

(1)

在此处输入图片说明

Expected Result colPosition = 1

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

Expected Result colPosition = 5

Here is a solution using the Excel Interop library (as tagged in the question). The below method will return a 1-based column index of the first cell in a given row. 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 .

    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). Using ClosedXML you would do the following (this is taken right from their webpage):

Get it right off the NuGet packages. Install-Package ClosedXML -Version 0.93.1

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.Workbook xlWB = Globals.ThisAddIn.Application.ActiveWorkbook;
Excel.Worksheet xlWS = xlWB.ActiveSheet;
int firstRow = xlWS.UsedRange.Row;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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