How to have excel addin read rows from a worksheet until there is more data?

I started writing Com addin for Excel 2003 using C #. I am looking for a code example showing how to read cell data from an active sheet. I saw that you can write code like this:

Excel.Range firstCell = ws.get_Range("A1", Type.Missing);
Excel.Range lastCell = ws.get_Range("A10", Type.Missing);
Excel.Range worksheetCells = ws.get_Range(firstCell, lastCell);

to capture a range of cells. What I can use is how to read cell data when you don't know how many rows of data there are. I can determine the starting line from which the data will start, but there will be an odd number of data lines to read.

Can someone provide me an example of how to read rows from a worksheet until you meet a row of empty cells?

Also does anyone know how to capture a range of cells selected by the user?

Any help would be greatly appreciated. This seems like a powerful tool for developers, but it's hard for me to find detailed documentation to help me learn it :)

+3
source share
2 answers

I can think of two approaches. The first option is to use a named range, not a cell position. In this case, you can, for example, name A1: A10 “MyList” and read the contents in the array using

Excel.Range range = worksheet.get_Range("MyList", Type.Missing);
object[,] data = (object[,])range.Value2;

, (, ), .
, , . , , (, 100 ), . , - , startRow , :

     int startRow = 1;
     bool hasContent = false;

     int row = startRow;
     do
     {
        var cell = (Excel.Range)sheet.Cells[row,1];
        if (cell.Value2 != null)
        {
           hasContent = true;
           row++;
        }
     }
     while (hasContent);
+3

, "".

var lastExcel = worksheet.Rows.get_End(XlDirection.xlDown); lastExcel.Cells[worksheet.Rows.get_End(XlDirection.xlUp).Row + 1, 1].Value2 = "End";

0

Source: https://habr.com/ru/post/1744633/


All Articles