Click here to Skip to main content
5,788,961 members and growing! (20,892 online)
Email Password   helpLost your password?
Languages » C# » Applications     Intermediate License: The Code Project Open License (CPOL)

Simple Excel Automation using C#

By Gigy

Simple Excel Automation using C#
C#, Windows, .NET, Visual Studio, Dev

Posted: 28 Dec 2006
Updated: 28 Dec 2006
Views: 76,813
Bookmarked: 48 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
20 votes for this Article.
Popularity: 3.70 Rating: 2.84 out of 5
7 votes, 35.0%
1
1 vote, 5.0%
2
1 vote, 5.0%
3
6 votes, 30.0%
4
5 votes, 25.0%
5

Sample Image - Simple_Excel_Automation.jpg

Introduction

Sample screenshot

Quite simple way of creating the MS Excel document through C# language.

Background

Minimum understanding of C# language buzz

Using the code

Create a new project, for simplicity, create a Windows application, go ahead and right click on References in the Solution Explorer, and select Add Reference… When the Add Reference window comes up, select the COM tab. This will list all Component names which are available on your machine. Since we are going to use MS Excel, you will scroll down until you find: Microsoft Excel 11.0 Object Library. You can even do the same thing PIAs. In the code I have used PIA.

I have created a very simple wrapper class for Excel  object model . The code will be given below. This project also has the error provider functionality to make sure that user will enter values for all the fields.

Create button click event. Here we checking whether all fields are filled and then call the CreateFile() function in Excel wrapper class

        private void btnCreate_Click(object sender, System.EventArgs e)
        {
            ExcelAuto excel = new ExcelAuto();
            ArrayList array = new ArrayList();
            bool filled = true;
            
            if ( ( txtName.Text).Trim().Length.Equals(0) )
            {
                errorProvider.SetError(txtName,"cannot be empty" );
                filled = false;
            }
            if( ( txtAge.Text ).Trim().Length.Equals(0) )
            {
                errorProvider.SetError( txtAge,"cannot be empty" );
                filled = false;
            }
            if( ( txtDesignation.Text ).Trim().Length.Equals(0) )
            {
                errorProvider.SetError( txtDesignation,"cannot be empty" );
                filled = false;
            }
            if( ( txtPlace.Text ).Trim().Length.Equals(0) )
            {
                errorProvider.SetError( txtPlace,"cannot be empty" );
                filled = false;
            }
            if( ( txtEmail.Text ).Trim().Length.Equals(0) )
            {
                errorProvider.SetError( txtEmail,"cannot be empty" );
                filled = false;
            }
            if( ( txtCompany.Text ).Trim().Length.Equals(0) )
            {
                errorProvider.SetError( txtCompany,"cannot be empty" );
                filled = false;
            }
            
            if ( filled == true )
            {
                array.Insert(0,txtName.Text);
                array.Insert(1,txtAge.Text);
                array.Insert(2,txtDesignation.Text);
                array.Insert(3,txtCompany.Text);
                array.Insert(4,txtPlace.Text);
                array.Insert(5,txtEmail.Text);
    
                excel.CreateFile(array);
            }
        }

Excel File creation Code

        public void CreateFile(ArrayList array)
        {
            object missing = System.Reflection.Missing.Value;
            object fileName = "normal.dot";
            object newTemplate = false;
            object docType = 0;
            object isVisible = true;
            
            ExcelApp = new Excel.ApplicationClass();
            ExcelApp.Visible = true;
            objBook = ExcelApp.Workbooks.Add(missing);
            objSheet = (Excel.Worksheet)objBook.Sheets["Sheet1"];
            objSheet.Name = "It's Me";

            objSheet.Cells[1, 1] = "Details";
            objSheet.Cells[2, 1] = "Name : "+ array[0].ToString();
            objSheet.Cells[3, 1] = "Age : "+ array[1].ToString();
            objSheet.Cells[4, 1] = "Designation : " + array[2].ToString();
            objSheet.Cells[5, 1] = "Company : " + array[3].ToString();
            objSheet.Cells[6, 1] = "Place : " + array[4].ToString();
            objSheet.Cells[7, 1] = "Email : "+array[5].ToString();

            objSheet.get_Range("A1", "A1").Font.Bold = true;
            objSheet.get_Range("A1", "A6").EntireColumn.AutoFit();
            objSheet.get_Range("A1","A7").BorderAround(Excel.XlLineStyle.xlContinuous,
                       Excel.XlBorderWeight.xlMedium,Excel.XlColorIndex.xlColorIndexAutomatic,
                       Excel.XlColorIndex.xlColorIndexAutomatic);
    
            
        }

Conclusion

The interop assemblies provide a lot of options for working with Excel data, both reading and writing. I hope this article gives you a head start in controlling Excel from .NET and C#. Some experiment with the object model will help you to get that hands on

History

First draft 29 December 2006

License

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

About the Author

Gigy


Gigy is a Software professional from India, now living in United States of America. He is having over 9 years of experience in various phases of software development. Worked in the capacity of Project Leader, Senior Software Engineer, Senior Programmer and Programmer in the development and maintenance of applications & products related to Online Banking, Insurance Brokerage, Image Processing, Healthcare Domain, Simulation, Graphics, Automation, Add - Ins and Porting.

He has worked in versatile technolgies viz. C, C++, MFC, Visual C++, COM, DCOM, ATL, Windows Services and Visual Studio IDE. Currently working in .Net Technologies - AJAX, C#, Visual Basic.NET, Managed C++, ASP.NET, SOAP, XML, DTD, XSL, Web Services and Visual Studio. NET 2005, 2008 IDEs.

He is presently working with NCR in Internet Banking Technologies. He has also worked with world reputed companies like Accenture, General Electric and Mphasis.



www.gigyonline.com
Occupation: Software Developer (Senior)
Company: NCR
Location: United States United States

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 13 of 13 (Total in Forum: 13) (Refresh)FirstPrevNext
Questionevent managment from excel to c#membermelloulmoti11:48 21 Mar '07  
GeneralVisual Studio version ?memberRansom8:10 4 Jan '07  
GeneralRe: Visual Studio version ?memberGigy17:20 4 Jan '07  
GeneralRe: Visual Studio version ?memberRansom4:44 5 Jan '07  
GeneralError when running program examplememberKaj Sloth0:50 4 Jan '07  
GeneralRe: Error when running program examplememberGigy17:37 4 Jan '07  
GeneralRe: Error when running program examplememberGigy17:48 4 Jan '07  
GeneralRe: Error when running program examplememberTompa@Physc.Su.Se4:10 16 Jan '07  
GeneralRe: Error when running program examplememberTann5:08 12 Feb '07  
QuestionHow to extract image embeded in excel cellsmembershellymidha19:08 3 Jan '07  
AnswerRe: How to extract image embeded in excel cellsmemberrvidhi2:30 15 Apr '07  
GeneralRe: How to extract image embeded in excel cellsmemberprivacy space1:15 19 Sep '07  
GeneralRe: How to extract image embeded in excel cellsmemberBarbaMariolino23:22 11 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Dec 2006
Editor: Paul Conrad
Copyright 2006 by Gigy
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project