Blue Theme Orange Theme Green Theme Red Theme
 
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual C# » Excel Automation in .Net

Excel Automation in .Net

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

Total page views :  54657
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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. 


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Click Here for 6 Months Free! Powerful ASP.NET Hosting at your Fingertips!
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 | Delete | 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 | Delete | Modify | 
Re: Conditional Formatting by Thiagarajan On November 6, 2007
I guess, the first option would be efficient.
Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.