user3574492
user3574492

Reputation: 6435

How to access an Excel WorkSheet cell in c#

I am using the Microsoft.Office.Interop.Excel namepace in C# to access Excel Worksheets.

I am having a bit of trouble with accessing a particular cell in a worksheet.

This is what I have so far:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input.Manipulations;
using Application = Microsoft.Office.Interop.Excel.Application;




namespace excelProgram
{
    class Program
    {
        [STAThreadAttribute]
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.openWorkSheet();
            Console.ReadKey(true);
        }


        private void openWorkSheet()
        {
            var xl= new Application();
            xl.Visible = true;
            xl.Workbooks.Open(@"C:\Documents and Settings\user\Desktop\Book1.xls");

        }


    }
}

I created an Application() object which opens up an Excel workbook on my PC. This works fine however I don't know how to access a particular Cell in a worksheet within a Workbook e.g. cell B1.

Could anybody help?

Upvotes: 4

Views: 3989

Answers (1)

gembird
gembird

Reputation: 14053

Get reference to particular sheet and then to particular range, e.g. like this.

(Example uses reference to Excel 2007 PIA: C:\Windows\assembly\GAC\Microsoft.Office.Interop.Excel\12.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll)

using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using Excel = Microsoft.Office.Interop.Excel;

Application excelApplication = new Excel.Application
{
    Visible = true,
    ScreenUpdating = true
};

_Workbook workbook = excelApplication.Workbooks.Open(@"C:\Temp\Book1.xlsx");
_Worksheet sheet = workbook.Worksheets[1];
Range range = sheet.Range["B1"];
range.Formula = "Test";

excelApplication.Quit();

Upvotes: 4

Related Questions