user2274204
user2274204

Reputation: 345

How to read from specific sheet in excel by name

I have excel that contains 4 sheets (Cars,Models,Customers,Contact) i have this code below. I need to read from specific sheet in the excel (Tab), how to do this ? I am using Microsoft office Interop excel

        string Mysheet = @"C:\MSFT Site Account Updates_May 2015.xlsx";
        var excelApp = new Excel.Application();
        Excel.Workbooks books = excelApp.Workbooks;
        Excel.Workbook sheets = books.Open(Mysheet);

        for (int i = 1; i < 2; i++)
        {
            string Name = ((excelApp.Cells[i, 1] as Excel.Range).Value);
            string SiteUrl = ((excelApp.Cells[i, 4] as Excel.Range).Value);
            Console.WriteLine("Account created");

        }

Thank you all

Upvotes: 4

Views: 14374

Answers (2)

BR.
BR.

Reputation: 61

var workbook = books.Open(Mysheet);
var worksheet = (Worksheet) workbook.Sheets["Customers"];

Console.WriteLine(worksheet.Cells[2, 2]); // for example...

Upvotes: 3

Charles Mager
Charles Mager

Reputation: 26223

You need to get the Worksheet for the sheet you want to read data from. To get range A1 from Cars, for example:

var app = new Application();
Workbooks workbooks = app.Workbooks;
Workbook workbook = workbooks.Open(@"C:\MSFT Site Account Updates_May 2015.xlsx");

Worksheet sheet = workbook.Sheets["Cars"];

Range range = sheet.Range["A1"];

Upvotes: 2

Related Questions