learnAsWeGo
learnAsWeGo

Reputation: 2282

Accessing Excel Cells Using C#

For now just want to be able to access an excel cells value and print that value in my console window.

A few of other ways I have tried:

System.Console.WriteLine(Mysheets.Cells[1,1].Tostring);

Note that the method above, after hitting period after the brackets intellisense only gives me option to equals, gethashcode, get type or two string. I saw some calling .value after the brackets but I am not given option to do so.

using Excel = Microsoft.Office.Interop.Excel;

class Program
{
    private static Excel.Workbook MyBook = null;
    private static Excel.Application MyApp = null;
    private static Excel.Worksheet MySheet = null;
    private static Excel.Range MyRangeOne = null;

    public static void Main()
    {
        string path = @"Z:\New folder\Test1234.xlsx";
        MyApp = new Excel.Application();
        MyApp.Visible = true;
        MyBook = MyApp.Workbooks.Open(path);
        MySheet = (Excel.Worksheet)MyBook.Worksheets[1];
        MyRangeOne = (Excel.Range)MySheet.Cells[1,1];

        try {
            System.Console.WriteLine(MySheet.Name);
            System.Console.WriteLine(MyRangeOne.Value);
        }
        catch(System.Exception err){
            System.Console.WriteLine(err.Message);
        }
    }
}

Have also tried

=Myrangeone.item[1,1].value. Keep getting the following error:

Object reference not set to an instance of an object

Amazing how difficult this is.

Upvotes: 0

Views: 302

Answers (1)

Sergei Yendiyarov
Sergei Yendiyarov

Reputation: 535

I recommend you to use this library for Excel sheet processing EPPlus. Your way of processing Excel files is not very efficient. So please check out it here.

This library can be installed via NuGet package manager. It is very easy to use.

Upvotes: 1

Related Questions