Click here to Skip to main content
Licence CPOL
First Posted 23 Nov 2010
Views 11,177
Downloads 204
Bookmarked 31 times

A Handy-Dandy Little Class for Accessing Excel Worksheet Cells

By | 1 Dec 2010 | Article
A class that accepts a reference to an Excel.Worksheet and lets you use an overloaded subscript operator to cleanly and intuitively read/write the Value2 of Excel cells, and get the Excel.Range corresponding to a given cell.

Introduction

Sometimes, when you're using the Excel.Interop classes, you want to open a worksheet from code and tweak the values of various cells. It's hard to remember the syntax.

oSheet = (Excel.Worksheet)oBook.Worksheets[1];
((Excel.Range)oSheet.Cells[1, 1]).Value2 = "blah";

I don't know about you, but I might like to encapsulate the Excel.Worksheet object I am using in a nice class with perhaps an operator [] overload, so I don't have to remember crazy syntax all the day long or be looking up code snippets and copying and pasting. I'm thinking that code of the form:

cellObj[1, 1]="blah";
int myCellValue = Convert.ToInt32(cellObj[1,2]);

is perhaps a bit more readable. So let's see if we can't make a class to help us with this.

ExcelCell Class

First, let's dive right into the meat. Here's the definition of our class, ExcelCell, which encapsulates the Excel.Worksheet object from Excel and allows access to individual cells.

using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
 
public class ExcelCell : Object
{
    private Excel.Worksheet oSheet;
 
    public ExcelCell(Excel.Worksheet oSheet)
    {
        this.oSheet = oSheet;
    }
 
    public object this[int row, int column]
    {
        get
        {
            if (oSheet == null)
                throw new InvalidOperationException(
                "Excel.Worksheet reference is null.");
            return ((Excel.Range)oSheet.Cells[row, column]).Value2;
        }
        set
        {
            if (oSheet == null)
            throw new InvalidOperationException(
                "Excel.Worksheet reference is null.");
            ((Excel.Range)oSheet.Cells[row, column]).Value2 = value;
        }
    }
 
    public Excel.Range GetRange(int row, int column)
    {
        if (oSheet == null)
            throw new InvalidOperationException(
        "Excel.Worksheet reference is null.");
        return ((Excel.Range)oSheet.Cells[row, column]);
    }
}

Note: You should make sure that you have the Microsoft.Office.Core and Microsoft.Office.Interop.Excel modules loaded as references in your project. They can be version 12 and up.

Using the Class

To use the class, say you have an instance of Excel.Application open and an instance of Excel.Workbook open as well (in .xls or .xlsx etc. format), and your instances are named oExcel and oBook, respectively. Let's see this class in action:

ExcelCell cell = new ExcelCell((Excel.Worksheet)oBook.Worksheets[1]);
 
cell[4, 2] = "happy";
cell[4, 4] = "day"; // sets Value2

int cellValue = Convert.ToInt32(cell[4,5]);
// reading a cell -- very straightforward.

And that's all she wrote!

Points of Interest

This class is interesting in that it reveals how to overload the [,] operator. A quick Google search can also find you the information, but watch how simplified your Excel programming gets after putting this class in your program.

History

  • 23 Nov. 2010: Article submitted.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Brian C Hart

Software Developer (Senior)
Corrugated Technologies, Inc.
United States United States

Member

Follow on Twitter Follow on Twitter
From Fridley, Minnesota and I like computer programming! When I got started, I was working mostly with Windows GUI programming in C/C++. Then later on I worked with COM/DCOM for a school internship. I used COM/DCOM to write an ad hoc cluster server and job-running environment for a cluster of 24 Windows-based high-end visualization workstations. I moved on to C# and have been working in C# and Windows Forms ever since. I have yet to embrace Silverlight Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralAlternative Excel component PinmemberCikaPero0:38 28 Mar '11  
GeneralThanks - This cleaned up my code considerably. Pinmemberrajaquila4:17 22 Dec '10  
GeneralMy vote of 5 Pinmemberthatraja2:45 30 Nov '10  
GeneralRe: My vote of 5 PinmemberBrian C. Hart, Ph.D.10:04 1 Dec '10  
GeneralVery cool, but even better if you... PinmemberDaveX8615:54 29 Nov '10  
GeneralMore, more PinmemberJohn Whitmire5:05 29 Nov '10  
GeneralRe: More, more PinmemberBrian C. Hart, Ph.D.5:16 29 Nov '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 1 Dec 2010
Article Copyright 2010 by Brian C Hart
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid