Listing C
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim excel As Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook
Dim ws As Microsoft.Office.Interop.Excel.Worksheet
Dim rng As Microsoft.Office.Interop.Excel.Range
Try
excel = New Microsoft.Office.Interop.Excel.Application
wb = excel.Workbooks.Add()
ws = wb.ActiveSheet()
rng = ws.Range("A1")
rng.Value = "BuilderAU.com.au"
rng = ws.Range("A3")
rng.Value = "Quarter"
rng = ws.Range("B3")
rng.Value = "Sales"
rng = ws.Range("A5")
rng.Value = "First"
rng = ws.Range("B5")
rng.Value = 1000.0
rng = ws.Range("A6")
rng.Value = "Second"
rng = ws.Range("B6")
rng.Value = 2000.0
rng = ws.Range("A7")
rng.Value = "Third"
rng = ws.Range("B7")
rng.Value = 4500.0
rng = ws.Range("A8")
rng.Value = "Fourth"
rng = ws.Range("B8")
rng.Value = 4000.0
rng = ws.Range("A10")
rng.Value = "Total"
rng = ws.Range("B10")
rng.Formula = "=@Sum(B5..B8)"
rng.Calculate()
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
End Sub
Only the code for a button is included. (Listing D contains the equivalent C# code.)
Listing D
private void button1_Click(object sender, System.EventArgs e) {
Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
Microsoft.Office.Interop.Excel.Range rng = null;
object missing = Type.Missing;
try {
excel = new Microsoft.Office.Interop.Excel.Application();
wb = excel.Workbooks.Add(missing);
ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
rng = ws.get_Range("A1", missing);
rng.Value2 = "BuilderAU.com.au";
rng = ws.get_Range("A3", missing);
rng.Value2 = "Quarter";
rng = ws.get_Range("B3", missing);
rng.Value2 = "Sales";
rng = ws.get_Range("A5", missing);
rng.Value2 = "First";
rng = ws.get_Range("B5", missing);
rng.Value2 = 1000.0;
rng = ws.get_Range("A6", missing);
rng.Value2 = "Second";
rng = ws.get_Range("B6", missing);
rng.Value2 = 2000.0;
rng = ws.get_Range("A7", missing);
rng.Value2 = "Third";
rng = ws.get_Range("B7", missing);
rng.Value2 = 4500.0;
rng = ws.get_Range("A8", missing);
rng.Value2 = "Fourth";
rng = ws.get_Range("B8", missing);
rng.Value2 = 4000.0;
rng = ws.get_Range("A10", missing);
rng.Value2 = "Total";
rng = ws.get_Range("B10", missing);
rng.Formula = "=@Sum(B5..B8)";
rng.Calculate();
excel.Visible = true;
wb.Activate();
} catch (COMException ex) {
MessageBox.Show("Error accessing Excel: " + ex.ToString());
} catch (Exception ex) {
MessageBox.Show("Error: " + ex.ToString());
} }
Here are a few notes on the code:
- A new Excel Workbook is created with the Add method of the Workbook's property of the Application object. This creates a workbook with one blank worksheet.
- The current sheet is accessed via the ActiveSheet property of the Worksheet object.
- A Range object is used to work with individual cells. The cell is accessed via its location on the sheet. For example, a title for the sheet (Techrepublic.com) is inserted at the first cell (A1 = column A and row 1). The Value property of the Range object is used to populate the cell.
- The Formula property of the Range object allows you to assign a formula to a cell or group of cells. In this example, the total of the second column of values is displayed.
- The Calculate method of the Range object processes the formula.
You may notice some differences between the C# and VB.NET versions. The get_Range method of the Worksheet class is used to instantiate the Range object in C#. In addition, the get_Range method features a second optional parameter so the Type.Missing value is used. Finally, the ActiveSheet object must be cast to the Worksheet class to use it. You should be prepared for such differences when using C# to utilise VBA COM objects.
The environment
Some readers have questioned the vulnerability of a user's system when working with Excel, but the examples in this article are built as Windows Form-based applications. The environment envisioned is an internal application, so security should not be as big an issue as if it is opened to the world. Using Excel via ASP.NET provides its own set of issues, and it is beyond the scope of this article.
Extending functionality
Integrating Excel with a .NET application allows you to easily and quickly provide powerful functionality within an application. The calculation and presentation features of Excel offer a wealth of options.
Do you need help with .Net? 



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:--
» 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.
» 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
» 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
» 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