How do I get an Excel range using row and column numbers in VSTO / C#?

后端 未结 9 1932
萌比男神i
萌比男神i 2020-12-05 13:07

I think the question sums it up. Given two integers for row and column or four integers for row and column for the two corners of a range, how do I get a range object for th

相关标签:
9条回答
  • 2020-12-05 13:49

    Try this, works!

    Excel.Worksheet sheet = xlWorkSheet;
    Excel.Series series1 = seriesCollection.NewSeries();
    Excel.Range rng = (Excel.Range)xlWorkSheet.Range[xlWorkSheet.Cells[3, 13], xlWorkSheet.Cells[pp, 13]].Cells;
    series1.Values = rng;
    
    0 讨论(0)
  • 2020-12-05 13:50

    you can retrieve value like this

    string str = (string)(range.Cells[row, col] as Excel.Range).Value2 ;
    

    select entire used range

    Excel.Range range = xlWorkSheet.UsedRange;
    

    source :

    http://csharp.net-informations.com/excel/csharp-read-excel.htm

    flaming

    0 讨论(0)
  • 2020-12-05 13:55

    UsedRange work fine with "virgins" cells, but if your cells are filled in the past, then UsedRange will deliver to you the old value.

    For example:

    "Think in a Excel sheet that have cells A1 to A5 filled with text". In this scenario, UsedRange must be implemented as:

    Long SheetRows;
    SheetRows = ActiveSheet.UsedRange.Rows.Count;
    

    A watch to SheetRows variable must display a value of 5 after the execution of this couple of lines.

    Q1: But, what happen if the value of A5 is deleted?

    A1: The value of SheetRows would be 5

    Q2: Why this?

    A2: Because MSDN define UsedRange property as:

    Gets a Microsoft.Office.Interop.Excel.Range object that represents all the cells that have contained a value at any time.


    So, the question is: Exist some/any workaround for this behavior?

    I think in 2 alternatives:

    1. Avoid deleting the content of the cell, preferring deletion of the whole row (right click in the row number, then "delete row".
    2. Use CurrentRegion instead of UsedRange property as follow:

    Long SheetRows;
    SheetRows = ActiveSheet.Range("A1").CurrentRegion.Rows.Count;
    
    0 讨论(0)
提交回复
热议问题