Click here to Skip to main content
Licence CPOL
First Posted 26 Aug 2007
Views 195,560
Downloads 6,308
Bookmarked 71 times

Using C# to Create an Excel Document

By | 26 Aug 2007 | Article
Shows how to create an Excel document using C# and formatting the cells
Screenshot - excell.gif

Introduction

Microsoft Excel is widely used in business because it offers the ability to present data to business executives in a way that makes sense to them. In this article, we are going to learn how easy it is to create an Excel document using C#.

Background

While looking to find an easy solution of how to read and write into a spreadsheet, I came across an article on the Microsoft site, How To Use ADO.NET to Retrieve and Modify Records in Excel. This is a wonderful article; however, formatting the data and the cosmetics of the document is not possible using this approach.

Using the Code

In order to use the class, you must add as a reference the Microsoft Excel XX.X Object Library in your project; this is a COM component; adding in Visual Studio is straight forward. Right click on your project on the Solution explorer and you should see the add reference option. Once selected, click the COM tab and look for the Excel library.
Once added, cut and paste the class below:

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace ExcelExample
{
    class CreateExcelDoc
    {
        private Excel.Application app = null;
        private Excel.Workbook workbook = null;
        private Excel.Worksheet worksheet = null;
        private Excel.Range workSheet_range = null;
        public CreateExcelDoc()
        {
            createDoc(); 
        }
        public void createDoc()
        {
            try
            {       
                app = new Excel.Application();
                app.Visible = true;
                workbook = app.Workbooks.Add(1);
                worksheet = (Excel.Worksheet)workbook.Sheets[1];
            }
            catch (Exception e)
            {
                Console.Write("Error");
            }
            finally
            {
            }
        }

public void createHeaders(int row, int col, string htext, string cell1,
string cell2, int mergeColumns,string b, bool font,int size,string
fcolor)
        {
            worksheet.Cells[row, col] = htext;
            workSheet_range = worksheet.get_Range(cell1, cell2);
            workSheet_range.Merge(mergeColumns);
            switch(b)
            {
                case "YELLOW":
                workSheet_range.Interior.Color = System.Drawing.Color.Yellow.ToArgb();
                break;
                case "GRAY":
                    workSheet_range.Interior.Color = System.Drawing.Color.Gray.ToArgb();
                break;
                case "GAINSBORO":
                    workSheet_range.Interior.Color = 
			System.Drawing.Color.Gainsboro.ToArgb();
                    break;
                case "Turquoise":
                    workSheet_range.Interior.Color = 
			System.Drawing.Color.Turquoise.ToArgb();
                    break;
                case "PeachPuff":
                    workSheet_range.Interior.Color = 
			System.Drawing.Color.PeachPuff.ToArgb();
                    break;
                default:
                  //  workSheet_range.Interior.Color = System.Drawing.Color..ToArgb();
                    break;
            }
         
            workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
            workSheet_range.Font.Bold = font;
            workSheet_range.ColumnWidth = size;
            if (fcolor.Equals(""))
            {
                workSheet_range.Font.Color = System.Drawing.Color.White.ToArgb();
            }
            else {
                workSheet_range.Font.Color = System.Drawing.Color.Black.ToArgb();
            }
        }

        public void addData(int row, int col, string data, 
			string cell1, string cell2,string format)
        {
            worksheet.Cells[row, col] = data;
            workSheet_range = worksheet.get_Range(cell1, cell2);
            workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
            workSheet_range.NumberFormat = format;
        }    
    }
}

Let's Go Over the Class

The first thing we do is declare the variables that are responsible for creating an Excel document.

  • private Excel.Application app = null; creates the Excel document
  • private Excel.Workbook workbook = null; create the workbook in the recently created document
  • private Excel.Worksheet worksheet = null; allows us to work with current worksheet
  • private Excel.Range workSheet_range = null; allows us to modify cells on the sheet

Note that the variables are not initialized; since they will be initialized in the constructor.

The Class has Two Methods

The class has only two methods: createHeaders and addData. Both of them take almost similar arguments. The createHeaders takes more arguments since headers must be noticeable as such. Let's explain what the arguments are:

  • row,col -- They are used to tell Excel where in the cell we want the text
  • htext -- This variable will hold the text for the header
  • cell1,cell2 -- This will be used to specify what cells we will use, e.g. A1:B1
  • mergeColumns -- It holds the number of cells we want to merge in a cell
  • b -- It will hold the color of the background for the chosen cell
  • font -- True or False for the font of the text on the selected cell
  • size -- To specify the size of the cell
  • fcolor-- Specify the color font

Below is the non-similar variable used in the addData method:

  • format -- It is used to tell Excel what time of format we want

How to Use the Class

Below is an example of how to use the class and if everything goes well; you should see the spreadsheet.

CreateExcelDoc excell_app = new CreateExcelDoc();         
//creates the main header
excell_app.createHeaders(5, 2, "Total of Products", "B5", "D5", 2,"YELLOW",true,10,"n");
//creates subheaders
excell_app.createHeaders(6, 2, "Sold Product", "B6", "B6", 0, "GRAY", true,10,"");
excell_app.createHeaders(6, 3, "", "C6", "C6", 0, "GRAY", true,10,"");
excell_app.createHeaders(6, 4, "Initial Total", "D6", "D6", 0, "GRAY", true,10,"");
//add Data to cells
excell_app.addData(7, 2, "114287", "B7", "B7","#,##0");
excell_app.addData(7, 3, "", "C7", "C7", "");
excell_app.addData(7, 4, "129121", "D7", "D7", "#,##0");
//add percentage row
excell_app.addData(8, 2, "", "B8", "B8", "");
excell_app.addData(8, 3, "=B7/D7", "C8", "C8", "0.0%");
excell_app.addData(8, 4, "", "D8", "D8", "");
//add empty divider
excell_app.createHeaders(9, 2, "", "B9", "D9", 2, "GAINSBORO", true, 10, "");

Enjoy it!

History

  • 26th August, 2007: Initial post

License

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

About the Author

Hector Pacheco

Software Developer

United States United States

Member

Currently working as an application/web developer for a publishing company;
he has being using Dotnet and other related technologies for over 4 years.

He also does freelance web development.


twiter

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
GeneralMy vote of 5 Pinmemberkaramusti1:59 9 May '12  
GeneralMy vote of 4 Pinmembercodeprojectnidaved16:43 8 May '12  
GeneralMy vote of 1 PinmemberWebservice54869:49 26 Mar '12  
QuestionCreating nicely formatted Excel files, without Excel automation Pinmemberaron.sinoai4:57 24 Feb '12  
QuestionWhere do you dispose your excel objects PinmemberChenNoam23:04 6 Dec '11  
GeneralMy vote of 4 PinmemberSmileychonggo15:05 13 Oct '11  
GeneralMy vote of 5 PinmemberSAGKAN19:00 3 Oct '11  
QuestionThanks Pinmembermphoenixe20:39 29 Jul '11  
GeneralAmazing!!!! Pinmembersing72918:40 17 May '11  
GeneralMy vote of 5 Pinmembertomi_122:08 11 Apr '11  
GeneralMy vote of 2 PinmemberBjerner20:50 28 Sep '10  
QuestionHow to Make Bold in Part of an Excel Cell - Need Eargent help!!!!!!! Pinmembersupuna2u17:25 12 Sep '10  
GeneralAwesome PinmemberTuan Jinn23:07 31 Aug '10  
QuestionBackground color is different !!! Pinmembersamprog1:05 30 Jun '10  
AnswerRe: Background color is different !!! PinmemberDLChambers10:54 28 Jul '10  
GeneralRe: Background color is different !!! PinmemberChrisDesjardins5:00 2 Apr '12  
Generalnice Pinmemberguzufeng16:05 24 May '10  
QuestionHow to merge cells from two adjacent rows e.g A1 and A2? Pinmembersubaganapathyraman3:12 11 May '10  
QuestionExport to excel very slow.. any ideas how to make it faster?? PinmemberKiran Sabinkar23:43 20 Oct '09  
AnswerRe: Export to excel very slow.. any ideas how to make it faster?? PinmemberHector Pacheco16:24 21 Oct '09  
GeneralRe: Export to excel very slow.. any ideas how to make it faster?? PinmemberKiran Sabinkar20:28 21 Oct '09  
GeneralRe: Export to excel very slow.. any ideas how to make it faster?? PinmemberHector Pacheco12:48 24 Oct '09  
GeneralRe: Export to excel very slow.. any ideas how to make it faster?? PinmemberKiran Sabinkar20:41 24 Oct '09  
AnswerRe: Export to excel very slow.. any ideas how to make it faster?? Pinmembergg423723:43 15 Nov '09  
GeneralUsing Microsoft Open XML Format SDK to generate Excel files is much easier PinmemberMaciej Gren8:14 21 Aug '09  

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
Web04 | 2.5.120517.1 | Last Updated 26 Aug 2007
Article Copyright 2007 by Hector Pacheco
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid