Click here to Skip to main content
15,887,355 members
Articles / Productivity Apps and Services / Microsoft Office / Microsoft Excel
Tip/Trick

Operating on Excel Cells and Cell Ranges with C#

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
11 Nov 2015CPOL2 min read 27.3K   3   5
How to obtain a reference to a range of Excel cells for manipulation and then do so (operate on the range)

Operating on Ranges is not just for Oklahoma Veterinarians Anymore

When working with Excel spreadsheets from C#, you first need to specify which cell or cells (cell range) you want to reference before actually doing something with them. There are probably many ways to do this; I will show you how you can reference a single cell first, and then how you can reference multiple cells (a Range).

First, let's assume we've declared variables for the various fundamental parts of an Excel spreadsheet like so:

C#
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
. . .
        private ApplicationClass _xlApp;
        private Workbook _xlBook;
        private Sheets _xlSheets;
        private Worksheet _xlSheet;
        . . .

Now that those preliminaries have been handled (no pun intended), we can move on to referencing cells and ranges of cells, and operating on them.

Single-Celled Organisms are Organisms, Too

You can treat a cell as a range of one row, one column, this way:

C#
var annualContractProductsCell = (Range)_xlSheet.Cells[5, 1];

The arguments passed to the Cells are first the row index (5 above) and then the column index (1 above). So, row 5 and column 1 is now stored in annualContractProductsCell. So now we can manipulate that range (even though it's the most basic of ranges, a single cell), like so:

C#
annualContractProductsCell.Interior.Color = XlRgbColor.rgbLightGoldenrodYellow;

Home, Home on the Range

Now let's work on a true range of cells - from a designated row and column starting point to a designated row and column ending point. We do that like this for a range that spans several columns on a single row:

C#
private static readonly int COLUMN_HEADING_ROW = 7;
private static readonly int MONTH1_COL = 3;
private static readonly int MONTH13_COL = 15;
. . .
var monthHeadingsRange = _xlSheet.Range[_xlSheet.Cells[COLUMN_HEADING_ROW, MONTH1_COL], _xlSheet.Cells[COLUMN_HEADING_ROW, MONTH13_COL]];
monthHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Here's how we can do it for a range that does the opposite - one that spans several rows over a single column:

C#
private static readonly int DATA_STARTING_ROW = 8;
private static readonly int ITEMDESC_COL = 1;
private int _lastRowAdded; // this is incremented as rows are programmatically added to the spreadsheet
. . .
var descriptionColRange = _xlSheet.Range[_xlSheet.Cells[DATA_STARTING_ROW, ITEMDESC_COL], _xlSheet.Cells[_lastRowAdded, ITEMDESC_COL]];
descriptionColRange.Interior.Color = XlRgbColor.rgbLightGreen;

Be Kind to Platypi

What, though, if you don't want to use one of the predefined colors, such as XlRgbColor's rgbLightGoldenrodYellow, rgbSkyBlue, and rgbLightGreen shown above (wondrous as they are), but rather a custom one of your own? Never fear, this is also possible. First, define such colors like so:

C#
public static Color PLATYPUS_GREEN = Color.FromArgb(70, 128, 0);
public static Color PLATYPUS_ORANGE = Color.FromArgb(208, 102, 7);
public static Color PLATYPUS_BLUE = Color.FromArgb(0, 128, 128);
public static Color PLATYPUS_YELLOW = Color.FromArgb(255, 163, 0);
public static Color PLATYPUS_PURPLE = Color.FromArgb(47, 40, 73);

With those in place, you can now replace code like this:

C#
descriptionColRange.Interior.Color = XlRgbColor.rgbLightGreen;

...with code like this:

C#
descriptionColRange.Interior.Color = ColorTranslator.ToOle(PLATYPUS_GREEN);

Caveat Developtor

Note: You will need to add a Reference to Microsoft.Office.Interop.Excel.dll to your project for this code to work. I am using version 15.0.0.0 in my .NET 4.5 project (Runtime Version v2.0.50727)

License

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


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
QuestionAlternatively... Pin
Ian Klek12-Nov-15 3:18
Ian Klek12-Nov-15 3:18 
AnswerRe: Alternatively... Pin
B. Clay Shannon12-Nov-15 3:32
professionalB. Clay Shannon12-Nov-15 3:32 
GeneralRe: Alternatively... Pin
Ian Klek26-Nov-15 5:45
Ian Klek26-Nov-15 5:45 
GeneralRe: Alternatively... Pin
B. Clay Shannon26-Nov-15 7:15
professionalB. Clay Shannon26-Nov-15 7:15 
GeneralRe: Alternatively... Pin
B. Clay Shannon26-Nov-15 7:19
professionalB. Clay Shannon26-Nov-15 7:19 

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

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