A .NET application may be greatly enhanced by providing additional functional via Excel integration. This includes the number-crunching capabilities inherent in Excel, as well as charting and much more. Learn more about Excel and .NET integration.

In a recent column, we explored the process of integrating Microsoft Word with the .NET Framework. There are numerous integration possibilities as the full power of the Microsoft Office Suite is available. In this article, we examine another scenario involving Microsoft Excel.

VBA persists
We must point out that the Microsoft Office product suite utilises the Visual Basic for Applications (VBA), so a little knowledge of the Component Object Model (COM) object is helpful. However, the .NET COM interop feature makes it easy to utilise COM objects within a .NET application. Let's begin with an overview of the Excel object model.

Excel object model
Microsoft Excel provides literally hundreds of objects for programmatically working within its environment. The whole set is beyond the scope of this article, so let's examine a few objects to get up and running. Here are four common objects:

  • Application:
  • Represents the entire Excel application. It exposes a great deal of information about the running application, the options applied to that instance, and the current user objects open within the instance.

  • Workbook:
  • A single Excel workbook that may contain one or more worksheets.

  • Worksheet:
  • An individual Excel worksheet. Most of the properties, methods, and events of the Worksheet object are identical or similar to members provided by the Application and/or Workbook classes.

  • Range:
  • A range of cells within a worksheet. A Range object represents a cell, a row, a column, a selection of cells containing one or more blocks of cells, or even a group of cells on multiple sheets.

The object model begins with the Application class at the top, since it is the starting point for accessing Excel. Before you can begin working with the Excel object model via .NET COM interop, you must make it available to your project.

Using Microsoft Excel
The Microsoft Excel Object Library must be made available to your .NET project. If using Visual Studio .NET, a reference may be added to a project via the Project | Add Reference menu selection. The COM tab within the Add Reference window provides access to COM libraries installed on the system. Excel is listed as Microsoft.Excel, and the specific name will depend on the Excel version installed. I have Excel 2003 on my system, so the COM library is listed as Microsoft.Excel 11.0 Object Library. In addition, two namespaces are necessary:

  • Microsoft.Office.Interop.Excel:
  • Allows you to work with Excel objects via .NET interop.

  • System.Runtime.InteropServices:
  • Includes the COMException class, allowing you to properly handle COM-related exceptions.

The code snippet in Listing A loads and opens an Excel file from the local file system.

Listing A
Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
object  missing  = Type.Missing;
try  {
excel = new Microsoft.Office.Interop.Excel.Application();
wb = excel.Workbooks.Open("c:\\test.xls", missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
excel.Visible = true;
wb.Activate();
}  catch (COMException ex) {
MessageBox.Show("Error accessing Excel: " + ex.ToString());
} catch (Exception ex) {
MessageBox.Show("Error: " + ex.ToString());
}

(Listing B contains the equivalent VB.NET code.)

Listing B
Dim excel As Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook
Try
excel = New Microsoft.Office.Interop.Excel.Application
wb = excel.Workbooks.Open("c:\\test.xls")
excel.Visible = True
wb.Activate()
Catch ex As COMException
MessageBox.Show("Error accessing Excel: " + ex.ToString())
Catch ex As Exception
MessageBox.Show("Error: " + ex.ToString())
End Try

Here are a few notes on the code:

  • The Open method of the Workbooks object (accessed via the Application object) allows you to access an existing Excel file. Note: As a C# developer, the Type.Missing value is necessary since the Excel VBA object model accepts numerous optional parameters. The Type.Missing value allows you to pass nothing to the parameter, but still recognise it. VB.NET supports optional parameters to this approach.

  • The Application object is set to visible and the Workbook object is activated to make it show on the screen.

  • The catch blocks handle specific COM-related exceptions as well as general exceptions.

The previous code does not encompass a complete application, but demonstrates how Excel may be used in both C# and VB.NET. Let's take it a step further by manipulating the data within a worksheet.

Do you need help with .Net? Gain advice from Builder AU forums

Related links

Comments

1

sompop - 17/04/06

Hi there,
I would like to create excel by using vb.net, but i don't know every little piece that i have to do. I already added reference microsoft excel 11.0 library. when i run, it said my version is too old or invalid type. now i'm using .net framwork 1.1 ... i'm not sure if i have to d/l 2.0 version. would u recommend me what exactly i have to do ... thanks
i'm taking senior project
would u email me @ nanakogugu@hotmail.com

» Report offensive content

2

Prabhakar - 11/05/06

Thanks for this wonderful article

» Report offensive content

3

Prasad Vilas Lohar - 15/05/06

Hello Sir,
what the namespace do i need to import for this code ?

Please tell me

» Report offensive content

4

Boris Mikhailovski - 26/07/06

Microsoft Excel 11.0 Object Library
Office 2003 Update: Redistributable Primary Interop Assemblies

http://www.microsoft.com/downloads/details.aspx?FamilyID=3c9a983a-ac14-4125-8ba0-d36d67e0f4ad&DisplayLang=en

» Report offensive content

5

sunil - 18/08/06

getting exception as com object 0r class id missing while opening xl file through .net

» Report offensive content

6

Shalaka - 30/08/06

Hi
Can anyone help me?
i have web application (asp.net and C#) which needs to deal with Excel files
when i write following code in my application and execute application on client system it gives error as "access denied to file"

wb = excel.Workbooks.Open("c:\\test.xls", missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);

whereas when i execute same code on server which is same as development system it works fine

can anyone tell me the solution???

Thnx
Shalaka

» Report offensive content

7

Kishan Sheth - 12/10/06

----How To Open Excel File Using ASP.NET and C#----

I wanna open Excel file using asp.net and c#.
i have tried the following code but its not working... kindly help me out in opening a Excell file using asp.net and C#.

The code it tried is written here:--

using System.IO;
using System.Diagnostics;
protected void Button1_Click(object sender, EventArgs e)
{
Process aa = new Process();
aa.StartInfo.UseShellExecute = false;
aa.StartInfo.FileName = @"d:\kishan\KBook1.xls";
aa.Start();
}

» Report offensive content

8

Nikhil Kabadi - 03/11/06

An excellent article. Find below code to save the document.....

NOTE: path_Name is the directory path.

string path_Name = null;
.....
path_Name = "C:\\Folder1\\File1_.xls";
.....
wb_New.SaveAs(path_Name,Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);

» Report offensive content

9

Bibhuti Prasanna - 16/11/06

shalaka,

change the value of Identity Impersonate=true in the web.config file. giving admin rights to the aspnet user is futile.

Cheers,

» Report offensive content

10

Bibhuti - 17/11/06

hi, I would like to know how to pick up values from an excel cell which has errors. Say when u convert a number in a cell to text then a green triangle appears at the top left corner. From such a cell when I try to pick values using a data reader/ dataset, it returns null. I have also tried running a macro and disabling the background error checking and number to text error checking to false as in:

oBooks.Application.ErrorCheckingOptions.BackgroundChecking = false;
oBooks.Application.ErrorCheckingOptions.NumberAsText = false;

But it has proved to be of no use. Please help!

» Report offensive content

11

michael - 20/11/06

When saved as CSV( I may have several worksheets in xls, and each is saved as csv ) , message box does appear ( “Save changes ‘yes’ , ‘no’ , ‘cancel’ ) on close() . IF programmatically save 100 xls files as csv , would it be possible to avoid popping up this message box somehow ?

TIA
Michael

       public static void SaveAsAscii(string filename, string mode)
{
Excel.Application myExcelApp = new Excel.Application();
myExcelApp.Workbooks.Open(filename, 0, true, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);

foreach (Excel.Worksheet sheet in myExcelApp.Worksheets)
{
sheet.SaveAs(Path.Combine(Path.GetDirectoryName(filename), sheet.Name ) + "." + mode.ToLower(), Excel.XlFileFormat.xlCSV,
missing, missing, missing, missing, missing,
missing, missing, missing);
}
myExcelApp.Workbooks.Close();
myExcelApp.Quit();
}

» Report offensive content

12

Marco - 20/11/06

Hi there,

we are in trouble saving an Excel file we have just created programmatically. The trick is in using different versions of Excel spreading from 2000 to 2003. With xp/2k3 we reach our goal using Worksheet.Save(...), which doesn't work with 2000.
We have experimented success with 2000 using Application.SaveWorkspace(...), which works on XP and doesn't fail in 2k3.
However, in Excel 2k3 you will see the SaveAs Dialog box appear to the user, even if you have prevented alerts to be showed.

We are using Microsoft.Interop.Excel, and there is one more strange thing: the Application.DisplayAlerts property works in all version, if compiled from a machin with same version.
If you compile that code on a Office XP machine and execute it on a Office 2k3, it will result in an odd message "Old version...".
Compiling code on a Office 2k3 machine, however, will run succesfull the same code. This seams to lead to an Interop issue, based on differents CLASSID mapped to the same property.

So the relevant question: is possible to save an Excel file programmaticali regardless of the Excel version? It is unrelevant if the file has a format without backword compatibility (which is not, however, 'cause you can open a 2k3 file with Office 2K), we need just to persist the file.

Second, if the first question is answered "no", is there a way to "detect" the Excel version running (without serach the registry) and make some switch "web-like"?

Thank you for all kind of suggestion.

» Report offensive content

13

Anzljc - 22/12/06

Hello, nice article but I have the same problem like person in comment 1. I would be very very happy and pleased if you take time and send me the solution at anze_o@yahoo.com

Thanks in advance, Anzljc.

» Report offensive content

14

Gustavo - 03/01/07

Shalaka,

"Access denied" is not for file, but for RPC (Remote Procedure call) in Excel application (DCOM), you have to go to "Control Painel/Administrator Tools/Component services" look for DCOM, look for Excel (Name depends on Excel version, and the name should be thinks like "file of microsoft excel") , select properties and change security access for IIS user, do not put all access for user "every one"!!! Server security is very important...

Gustavo S. Borges

» Report offensive content

15

natalia - 11/01/07

hi , i hope you can help me
when i do this

oBook = oExcel.Workbooks.Open(nombrearchivo)

this message shows up
An unhandled exception of type 'System.InvalidCastException' occurred in system.windows.forms.dll
Additional information: Specified cast is not valid.
any ideas???

» Report offensive content

16

Mathueu Cupryk - 30/03/07

contents of datatable into excel spreadsheet in asp.net

need to look at a program that can put a datatable into an excel spreadsheet in asp.net 2.0 vb.net

Customer Shopper ID Year Period No Period Name Prestige Gross Sales Prestige Net Sales Prestige Discount Nb. Prestige Transactions
256039201 1 2005 12 Jan 64 50.15 -5.6 3

this is a datatable using the viewer built in.

Using Excel = Microsoft.Office.Interop.Excel;
public class ExcelPush
{
Excel.ApplicationClass _excel = new Excel.ApplicationClass();

public ExcelPush()
{
//
// TODO: Add constructor logic here
//
}

public Excel.Worksheet Activate()
{
// open new excel spreadsheet
try
{
Excel.Workbook workbook = _excel.Workbooks.Add(Type.Missing);
_excel.Visible = true;
Excel.Worksheet ws = (Excel.Worksheet)_excel.ActiveSheet;
ws.Activate();
return ws;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

return null;
}


public void AddItemToSpreadsheet(int row, int column, Excel.Worksheet ws, string item)
{
((Excel.Range)ws.Cells[row, column]).Value2 = item;
}
}




End Class

Private Sub cmdProceed_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles cmdProceed.Click
Dim dt As New DataTable
dt = _calendar.GetBusinessCalendarPeriod(txtPeriod.Text)
Dim selectedConnectionString As String = String.Empty
Dim selectedDBName As String = String.Empty
Dim selectedServerName As String = String.Empty
' Get the correct connection string and database name
If Not ddlDivisions.SelectedItem Is Nothing Then
For Each div As Division In _divisions
If div.Name = ddlDivisions.SelectedItem.Text Then
selectedDBName = div.DatabaseName
Exit For
End If
Next
End If

Dim rowNumber As Integer
Dim NewDataTable As DataTable
rowNumber = 0
For Each rw As DataRow In dt.Rows
NewDataTable = _customer.GetCustomerList(selectedDBName, rw)
****************************** Call excell routine.
Next

End Sub

Dim rowNumber As Integer
Dim NewDataTable As DataTable
rowNumber = 0
For Each rw As DataRow In dt.Rows
NewDataTable = _customer.GetCustomerList(selectedDBName, rw)
****************************** Call excell routine.
Next

» Report offensive content

17

murali - 24/05/07

i added the com component Microsoft.Excel 11.0 Object Library, but it showing error of name space Microsoft.Office.Interop.Excel,
what is the name space for Microsoft.Excel 11.0 Object Library, iam using framework 1.1

» Report offensive content

18

murali - 24/05/07

i added the com component Microsoft.Excel 11.0 Object Library, but it showing error of name space Microsoft.Office.Interop.Excel,
what is the name space for Microsoft.Excel 11.0 Object Library, iam using framework 1.1

» Report offensive content

19

Binu - 06/07/07

Thank you Very much
Today was my first day in my project. my team hasbeen searching for the code which can open up excel sheet from a .net application. Using the code given i could impress them... every one was searching hard for long time but i could provide the solution in 5 min... thanks a lot

» Report offensive content

20

Kiran - 01/10/07

Hello,
Can any one tell me when i run excel application using asp.net in IE it is working well but when i open in firefox mozilla it is giving an error that it is not at all taking the correct path of excel sheet , it is saying that have chaged the path of excel sheet .

» Report offensive content

21

Vaibhav - 30/10/07

Can any one tell me how to run the VBA file using VB.net code.

» Report offensive content

22

Swati - 08/11/07

Hi..
i am working on one asp.net(c#) application where i want to upload an excel file to sql server.How do i do it??? i have added a reference of Microsoft Office 11.0 object Library.....now what next to do??

» Report offensive content

23

tamarind - 14/11/07

hi
i am trying to open other excel formats in office 2007 using a code similar to above, i have changed the interop assemblies of version 12 but am still getting an error of old format? can yu please help?

» Report offensive content

24

tamarind - 14/11/07

hi
i am trying to open other excel formats in office 2007 using a code similar to above, i have changed the interop assemblies of version 12 but am still getting an error of old format? can yu please help? 0x80028018;

» Report offensive content

25

kirti - 08/03/08

Actully i m getting error for below lines:

Dim Excel As New Excel.ApplicationClass // here its showing error like " Type 'Excel.ApplicationClass' not defined "
Dim wbook As Excel.Workbook // here its showing error like " Type 'Excel.Workbook' not defined "
Dim wsheet As Excel.Worksheet // here its showing error like " Type 'Excel.Worksheet ' not defined "

i have added References mentioned below :
1.Microsoft Office 11.0 Object Library
2.Microsoft Excel 11.0 Object Library
still its showing error can anyone tell me its solution ASAP ?

» Report offensive content

26

stumpton - 30/04/08

Works like a dream. Thanks very much for that.

» Report offensive content

27

andresFang - 27/12/08

Hi, i got an COMException for invalide type, i solved this problem changing the regional conf of my pc, i have to set it in "english united states" and i fixed the problem, here is a link but it's in spanish

http://support.microsoft.com/kb/320369

i hope u can fix it if u get the same problem.

» Report offensive content

28

viengkham - 02/09/09

help me to solve error about use vb.net makes excel file

Private Sub cmdExportToExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExportToExcel.Click
Dim ExcelApp As New Excel.Application
Dim ExcelBooks As Excel.Workbook
Dim ExcelSheets As Excel.Worksheet

ExcelApp.Visible = True
ExcelBooks = ExcelApp.Workbooks.Add ' ERRER HERE
ExcelSheets = CType(ExcelBooks.Worksheets(1), Excel.Worksheet)

» Report offensive content

29

viengkham - 02/09/09

Can you help me to solve this Code for vb.net 2003 to make excel file 2007. When i run project it ERRER in code ExcelBooks = ExcelApp.Workbooks.Add
Thank you very much.

Private Sub cmdExportToExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExportToExcel.Click
Dim ExcelApp As New Excel.Application
Dim ExcelBooks As Excel.Workbook
Dim ExcelSheets As Excel.Worksheet

ExcelApp.Visible = True
ExcelBooks = ExcelApp.Workbooks.Add ' ERRER HERE
ExcelSheets = CType(ExcelBooks.Worksheets(1), Excel.Worksheet)

» Report offensive content

30

Steve - 27/10/09

Hi, thanks Tony Patton, awesome article - it works!.
Ideally for my application I want to create a program with vb 2008 express and have it as an addin in excel 2007. Can it be done with these name spaces dicussed here or does one need vb 2008 professional?

» Report offensive content

31

Madhan Kumar - 12/03/10

How do you handle hyperlinks in excel using vb.net/c#.net?
I have populated an excel file using vb.net and I need to add another column which will have hyperlinks to other files in the same folder as that of the excel file. I am stuck up with it right now. Any help would be greatly appreciated.

Thanks

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

31

Madhan Kumar - 03/12/10

How do you handle hyperlinks in excel using vb.net/c#.net? I have populated an excel file using vb.net and I need to add ... more

30

Steve - 27/10/09

Hi, thanks Tony Patton, awesome article - it works!. Ideally for my application I want to create a program with vb 2008 ... more

29

viengkham - 09/02/09

Can you help me to solve this Code for vb.net 2003 to make excel file 2007. When i run project it ... more

Log in


Sign up | Forgot your password?

  • Staff Microsoft shows off IE9 preview

    This week, highlights from Microsoft's MIX10 conference and more in the Roundup. Read more »

    -- posted by Staff

  • Chris Duckett IE9's H.264 vote killed Ogg

    In a split decision by the judges, the winner of the W3C/WHATWG video codec consensus is H.264, taking home the future of video playback on the internet while loser Ogg goes home with nothing but thoughts of what might have been. Read more »

    -- posted by Chris Duckett

  • Staff Google launches Apps Marketplace

    Google launches and app store, while Mozilla plans to re-write its open-source license. More of this week's news in the Roundup. Read more »

    -- posted by Staff

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!