Creating an Excel Spreadsheet programmatically using VB

Creating an Excel Spreadsheet programmatically using VB.NET
From:
http://www.vbdotnetheaven.com/UploadFile/ggaganesh/ExcelSpreadsheet04182005093012AM/Exc
elSpreadsheet.aspx
INTRODUCTION:
The Interoperability services make it very easy to work with COM Capable Applications such as
Word and Excel. This article reveals using Excel from a managed application. Excel is the
spreadsheet component of Microsoft Office 2000. The majority of Excel programmatic
functionality is exposed through Automation via the type library Excel9.olb. The intention of this
article is to express that a managed application can interrelate with Excel as a COM server.
The first step is to create a reference in our project to Excel 9.0 Objects Library.
By using Tlbimp tool we can generate Excel.dll.
TlbImp Excel9.olb Excel.dll.
By adding Excel.dll to our program we can use the functionality of the Excel.
Now let us see in detail how to create an Excel Spreadsheet? & Set values to the cell using
VB.NET. The codes for Creating, make visible, add a new workbook and to set a value for cell in
the Excel file is shown below.
1.
CREATING NEW EXCEL.APPLICATION:
2.
Dim exc As New Application ()
If exc Is Nothing Then
Console.WriteLine("ERROR: EXCEL couldn't be started")
Return 0
End If
TO MAKE APPLICATION VISIBLE:
3.
exc.set_Visible(0, true)
TO GET THE WORKBOOKS COLLECTION:
4.
Dim workbooks As Workbooks = exc.Workbooks
Dim workbook As _Workbook = workbooks.Add
XlWBATemplate.xlWBATWorksheet, 0)
TO GET THE WORKSHEETS COLLECTION:
5.
Dim worksheet As _Worksheet = CType(sheets.get_Item(1), _Worksheet)
If worksheet Is Nothing Then
Console.WriteLine("ERROR in worksheet == null")
End If
TO SET THE VALUE FOR CELL:
Dim range1 As Range = worksheet.get_Range("C1", Missing.Value)
If range1 Is Nothing Then
Console.WriteLine("ERROR: range == null")
End If
Const nCells As Integer = 1
Dim args1(1) As [Object]
args1(0) = nCells
range1.GetType().InvokeMember("Value", BindingFlags.SetProperty, Nothing, range1,
args1)
-1-
The Example:
Imports System
Imports System.Reflection ' For Missing.Value and BindingFlags
Imports System.Runtime.InteropServices ' For COMException
Imports Excel
Class AutoExcel
Public Shared Function Main() As Integer
Dim exc As New Application
If exc Is Nothing Then
Console.WriteLine("ERROR: EXCEL couldn't be started!")
Return 0
End If
exc.set_Visible(0, True)
Dim workbooks As Workbooks = exc.Workbooks
Dim workbook As _Workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet, 0)
Dim sheets As Sheets = workbook.Worksheets
Dim worksheet As _Worksheet = CType(sheets.get_Item(1), _Worksheet)
If worksheet Is Nothing Then
Console.WriteLine("ERROR: worksheet == null")
End If
Dim range1 As Range = worksheet.get_Range("C1", Missing.Value)
If range1 Is Nothing Then
Console.WriteLine("ERROR: range == null")
End If
Const nCells As Integer = 1
Dim args1(1) As [Object]
args1(0) = nCells
range1.GetType().InvokeMember("Value", BindingFlags.SetProperty, Nothing, range1, args1)
Return 100
End Function 'Main
End Class 'AutoExcel
Now let us observe how to send a single dimension array to Excel:
It is similar to set the value for the cell. Only change is we use array as args2[0] = array2.
Const nCell As Integer = 5
Dim range2 As Range = worksheet.get_Range("A1", "E1")
Dim array2(nCell) As Integer
Dim i As Integer
For i = 0 To (array2.GetLength(0)) - 1
array2(i) = i + 1
Next i
Dim args2(1) As [Object]
args2(0) = array2
range2.GetType().InvokeMember("Value", BindingFlags.SetProperty, Nothing, range2, args2)
End Function '__unknown
The OutPut:
-2-
Conclusion:
With the help of TlbImp.exe tool we can generate .NET assembly from Type library files and we
can use that functionality of Type library file in VB.NET.
Excel Connectivity in VB.NET
From: http://www.codeproject.com/useritems/Excel_Connectivity.asp
Introduction
Often we are in a need to convert Excel data to XML stream/XML file which can be used as a feed
to various applications like web services or middle tiers such as BizTalk 2004. There will be many
situations where we need to validate the format of Excel data sheet against a specified XML schema.
We will also be required to generate XML schema based on an Excel Work Sheet. This utility along
with the library will help you to accomplish the same.
The following are the salient features of this library:
1. Usage of Microsoft Jet Engine to connect to Excel.
2. Conversion of Excel Worksheet/Workbook to XML file and XML Schema.
3. Generation of XML file and XML Schema based on provided range.
-3-
4. Validation of Excel Worksheet/Workbook against the provided XML Schema.
5. Provision of batch processing capability.
In this article, we will discuss the implementation of the library functions. The library contains the
core functionality to access and manipulate Excel data.
The utility will merely call the appropriate functions from the library. In this way, one can use this
same library in ASP.NET applications also with minute changes.
Connectivity Options
There are two ways to manipulate an Excel file. It can be done either by using Microsoft Office
Component (check out here) or with Microsoft Jet Engine.
As per Microsoft recommendation, it is not advisable to use Office components on the server. It
means that if you want to use this library for a server application, it’s not a good idea to use the
Office component. So the connection will be done using Jet Engine.
Connection to Excel using Jet Engine
To connect to Excel, one can use OleDb objects that will treat Excel as a database, and then the
required information can be easily fetched by using SQL queries. The important steps that have to be
considered while connecting to Excel are as follows:

Connection String:
The connection string should be set to the OleDbConnection object. This is very critical as
Jet Engine might not give a proper error message if the appropriate details are not given.
Syntax: Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<Full Path of Excel
File>; Extended Properties="Excel 8.0; HDR=No; IMEX=1".

Definition of Extended Properties:
o Excel = <No>
One should specify the version of Excel Sheet here. For Excel 2000 and above, it is
set it to Excel 8.0 and for all others, it is Excel 5.0.
o
HDR= <Yes/No>
This property will be used to specify the definition of header for each column. If the
value is ‘Yes’, the first row will be treated as heading. Otherwise, the heading will be
generated by the system like F1, F2 and so on.
o
IMEX= <0/1/2>
IMEX
refers to IMport EXport mode. This can take three possible values.
-4-


IMEX=0
and IMEX=2 will result in ImportMixedTypes being ignored and the
default value of ‘Majority Types’ is used. In this case, it will take the first 8
rows and then the data type for each column will be decided.
IMEX=1 is the only way to set the value of ImportMixedTypes as Text. Here,
everything will be treated as text.
Loading of data in to Dataset
After successfully connecting to Excel using Jet Engine, it is easy to the load the data in to DataSet.
One has to write a query similar to ANSI-92 with the only changes being that each Excel sheet will
be treated as a table and the table name will be the sheet name with “$”. The range can also be
specified after the “$” sign.
Collapse
Public Function ImportAttendence(ByVal PrmPathExcelFile As String, ByVal
DataGrid1 As DataGrid)
Dim MyConnection As System.Data.OleDb.OleDbConnection
Try
''''''' Fetch Data from Excel
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New
System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; " & _
"data source='" & PrmPathExcelFile & " '; " & "Extended Properties=Excel 8.0;")
' Select the data from Sheet1 of the workbook.
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [sheet1$]",
MyConnection)
MyCommand.TableMappings.Add("Table", "Attendence")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
DataGrid1.DataSource = DtSet.Tables(0)
MyConnection.Close()
-5-
Catch ex As Exception
MyConnection.Close()
End Try
End Function
Extend your .NET application with Excel
From:
http://www.builderau.com.au/program/dotnet/soa/Extend_your_NET_application_with_Excel/0,339
028399,339211524,00.htm
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
-6-
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 (C#) 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.
-7-
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.
The VB.NET code in Listing C creates a new Excel sheet, inserts numbers, and performs a
calculation.
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())
-8-
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:
-9-





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.
- 10 -