Jolie
Jolie

Reputation: 11

C# how to read specifed cells from multiple sheet excel using interop?

I need to read from "B2" to "H10" ( 5 rows 7 column ) in the first Sheet and second sheet of the excel file. My code below worked for reading every cell from both sheets, how can I read the cells I need from both sheets? (I saw lots of solutions using activeworksheet without specifying which sheet it's reading which cannot solve my problem. )

        using Excel = Microsoft.Office.Interop.Excel;
        using System.Runtime.InteropServices;

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;

        string str;
        int rCnt;
        int cCnt;
        int rw = 0;
        int cl = 0;

        xlApp = new Excel.Application();

        xlWorkBook = xlApp.Workbooks.Open("PATH", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("sheetName");
        range = xlWorkSheet.UsedRange;

        rw = range.Rows.Count;
        cl = range.Columns.Count;


        for (rCnt = 1; rCnt <= rw; rCnt++)
        {

            for (cCnt = 1; cCnt <= cl; cCnt++)
            {

                str = ((range.Cells[rCnt, cCnt] as Excel.Range).Value2).ToString();
                MessageBox.Show(str);

            }

        }

Upvotes: 0

Views: 1221

Answers (2)

Jolie
Jolie

Reputation: 11

I found the solution, my code is updated below.

    using Excel = Microsoft.Office.Interop.Excel;
    using System.Runtime.InteropServices;

    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    Excel.Range range, sRange;

    string str;
    int rCnt;
    int cCnt;
    int rw = 0;
    int cl = 0;

    xlApp = new Excel.Application();

    xlWorkBook = xlApp.Workbooks.Open("PATH", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("sheetName");
    range = xlWorkSheet.Cells;
    sRange = range.Range["B2", "H10"];
    rw = sRange.Rows.Count;
    cl = sRange.Columns.Count;


    for (rCnt = 1; rCnt <= rw; rCnt++)
    {

        for (cCnt = 1; cCnt <= cl; cCnt++)
        {

            str = ((sRange.Cells[rCnt, cCnt] as Excel.Range).Value2).ToString();
            MessageBox.Show(str);

        }

    }

Upvotes: 1

Markus Deibel
Markus Deibel

Reputation: 1351

range = xlWorkSheet.Cells.get_Range("B2:H10").Select()

should do the trick

More examples can be found at https://www.add-in-express.com/creating-addins-blog/2013/10/15/excel-cell-values-formulas-formatting-csharp/

Upvotes: 0

Related Questions