Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » Visual C# » Excel Automation in .Net

Excel Automation in .Net

This article explains how to achieve excel automation in .Net.

Page Views : 82115
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

Excel Automation is a buzz word in both webapps and winapps. In the programming life (like Mr.Anderson neo) I guess almost every one could have come across this word. For others let me go further in detail. Excel Automation is automating some or all of the process involved in creating or updating excel worksheets.

The real life scenario of an excel automation can be a daily account maintenance where you have an excel sheet template with graphs and calculations already in place except the data. So you want the data to be pulled in from a database and written to the excel sheet. After this the template takes care of the data by manipulating for graph generation.

Analysis

For the above said scenario we can go for a simple console application in .Net. Why I didn't go for an ASP.Net web application? Because running a web application requires a browser to be opened and closed. This becomes tedious when you schedule the process using windows scheduler to occur in particular intervals. And running a console based application is quite easy.



Getting Started


Pardon me for beating around the bush. Now let us jump in to the good part (coding). For this automation process we need to follow the below steps

  1. Add a referrence to the Microsoft Excel object library COM component.

  2. Add the namespace Excel

  3. Instantiate the class Excel.ApplicationClass as below

    Excel.Application xl=new Excel.ApplicationClass();

  4. To open an excel file,

    Excel.Workbook wb=xl.Workbooks.Open(Environment.CurrentDirectory+"/SampleExcel.xls",0, false, 5, System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value,true, false, System.Reflection.Missing.Value, false, false, false);//Open the excel sheet

  5. To read cell(s) in the worksheet,

    Excel.Sheets xlsheets = wb.Sheets; //Get the sheets from workbook
    Excel.Worksheet excelWorksheet = (Excel.Worksheet)xlsheets[1]; //Select the first sheet
    Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("B4:FZ4", Type.Missing); //Select a range of cells
    Excel.Range excelCell2 = (Excel.Range)excelWorksheet.get_Range("A5:A5", Type.Missing); //Select a single cell
    Console.WriteLine(excelCell2.Cells.Value2.ToString()); //Print the value of the cell for a single cell selection
    System.Array myvalues = (System.Array)excelCell.Cells.Value2; //Assign it to an array
    string[] strArray = ConvertToStringArray(myvalues); //Convert array into String array
    foreach (string str in strArray)
    Console.WriteLine(" Text in Cell " + str); //Loop through the array to print the values in the cell




  6. To save a value in a cell

    excelCell2.Cells.Value2 = "SampleText"; //Assign a value to the cell
    wb.Save(); //Save the workbook

  7. Finally Quit the Excel Application

    xl.Quit();

Conclusion

Excel is a great tool to work with. When it comes to automating, we need to consider many things. Always remember to quit the excel application in code before exiting. If not, the memory consumed by the excel application will not be freed up. 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Thiagarajan Alagarsamy
Thiagu is living in Bangalore, India. His native is Madurai, a historic city in south India. He loves to code in C#. He frequents c# corner articles when he is not coding. Thiagu loves reading Jeffrey Archer and Sidney Sheldon novels. He is very much interested in Artificial Intelligence (AI). To view his blog - http://csharpnet.blogspot.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
VB.NET Code by Mahesh On January 8, 2007

Good intro article. However, you will get an exception if .xls file is not available.

I needed same in VB.NET and here is the converted code: 

Dim excelApp As ApplicationClass = New ApplicationClass
Dim excelBook As Workbook
excelBook = excelApp.Workbooks.Open(
"C:\SampleExcel.xls", 0, False, 5, _
System.Reflection.Missing.Value, System.Reflection.Missing.Value, _
False, System.Reflection.Missing.Value, System.Reflection.Missing.Value, _
True, False, System.Reflection.Missing.Value, False)

Dim excelSheets As Sheets = excelBook.Sheets
Dim wSheet As Worksheet = excelSheets(1)
Dim cell1 As Range = wSheet.Range("B4:FZ4", Type.Missing)
Dim cell2 As Range = wSheet.Range("A4:A5", Type.Missing)
cell2.Value2 =
"SampleText"

excelBook.Save()
excelApp.Quit()

Reply | Email | Modify 
Conditional Formatting by David On September 18, 2007

Suppose I want to grab a row in excel and make the font Bold and put a border around it. Which is more Efficient?

 

Range r = MyWorksheet.get_Range("A1", "W1");

r.Font.Bold = true;

r.Cells.Borders.Weight = 2;

 

OR

 

MyWorksheet.get_Range("A1", "W1").Font.Bold = true;

MyWorksheet.get_Range("A1", "W1").Cells.Borders.Weight = 2;

Reply | Email | Modify 
Re: Conditional Formatting by Thiagarajan On November 6, 2007
I guess, the first option would be efficient.
Reply | Email | Modify 
How to import data from Excel in to SQL database in 64 bit OS by Ajey On February 5, 2008
How to import data from Excel sheet in to database in ASP.NET 2.0 application running under 64 bit OS. The application is working fine in 32 bit OS. As OLEDB data provider is not supported in 64 bit OS the application is not working. Please do suggest me a solution. Thanks
Reply | Email | Modify 
Re: How to import data from Excel in to SQL database in 64 bit OS by Filip On March 21, 2008
Well you could use our Fast and Easy Read/Write Excel File .NET Component). You can even use our Free Spreadsheet C#/VB.NET Component in your commercial applications.
Reply | Email | Modify 
FORMATING OF NUMBERS by PRAMOD On February 6, 2008
SUGGEST HOW TO CONVERT A RANGE OF CELLS CONTAINIG NUMBERS IN INDIAN STYLE AS LABELS("XX,XX,XX,000.00) INTI NUMBERS IN US STYLE ,NOT AS LABELS BUT AS PURE NUMBERS( XXX,XXX,XXX.00)
Reply | Email | Modify 
About Multiline by AdygTulush On February 6, 2008
How can i programatically make a multiline? Manually it is possible by pressing ALT+ENTER Also is it possible in SQL db? You see i need a db of LETTERS containing RECIEVERS. Each LETTER has 1 or more RECIEVERS. The problem is user chooses a RECIEVER from a db and inputs it into my db of LETTERS in SQL. But amount of RECIEVERS in a record not available... It can be 1,2,3 or 4, max 10.
Reply | Email | Modify 
need help for exporting dataset to multiple sheet in excel in c# by hemant On September 26, 2008
hello frd i need code to export data from a dataset to excel using c#. the excel will have multiple sheet and after exporting should contain one table each....
Reply | Email | Modify 
nned code to save range of cells as image by Vinod On June 6, 2009
Can i get a code to save tgeh range of cells as image and send that image through an automated email.
Reply | Email | Modify 
Ouestion by Prabhu On June 15, 2009
I am getting error as threw an exception of type 'System.Runtime.InteropServices.COMException While opening the excel
Reply | Email | Modify 
Re: by Filip On July 3, 2009
Nice article Thiagarajan, but Excel Automation doesn't work if all clients that are using your application don't have Microsoft Excel installed on their computers. Check out GemBox 3rd party .NET component for Excel which works also on computers that don't have Microsoft Excel installed. It is free for commercial use if you need less then 150 rows and 5 sheets.

Filip
GemBox Software - .NET Components for Reading/Writing Excel files and Compund Documents files


Reply | Email | Modify 
Excel automation trickies by John On July 13, 2010
I have read good article about excel automation: Excel sheet processing
There is defined few important tricks
Reply | Email | Modify 
Creating Excel files on the Server without Office by MDeLeon On December 20, 2010
If you're creating Excel 2007/2010 files then give my API a try: http://closedxml.codeplex.com
Reply | Email | Modify 
Excel Automation by bharat On February 9, 2011
i want to know which is better one in C# .net to Excel or Asp.net to excel.
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.