Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleWrite data into an Excel workbook in Visual Basic .NET
DescriptionThis example shows how to write data into an Excel workbook in Visual Basic .NET.
KeywordsMicrosoft Office, Office, Excel, Microsoft Excel, write to Excel, color cell, format cell, color Excel cell, format Excel cell
CategoriesOffice, VB.NET
 

A Visual Basic .NET program can open the Excel application and use it as a server to manipulate Excel workbooks.

First open the Add References dialog. On the COM tab, select "Microsoft 12.0 Object Library" (or whatever version you have installed on your system).

Add the following using statement to make working with the Excel namespace easier. The "Excel =" part means you can use "Excel" as an alias for the namespace.

    Imports Excel = Microsoft.Office.Interop.Excel

This example uses the following code to open a workbook, add a new worksheet to it, write to the worksheet, save the changes, and close everything.

 
' Write into the Excel workbook.
Private Sub btnWrite_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnWrite.Click
    ' Get the Excel application object.
    Dim excel_app As New Excel.ApplicationClass()

    ' Make Excel visible (optional).
    excel_app.Visible = True

    ' Open the workbook.
    Dim workbook As Excel.Workbook = _
        excel_app.Workbooks.Open(FileName:=txtFile.Text)

    ' See if the worksheet already exists.
    Dim sheet_name As String = _
        DateTime.Now.ToString("MM-dd-yy")

    Dim sheet As Excel.Worksheet = FindSheet(workbook, _
        sheet_name)
    If (sheet Is Nothing) Then
        ' Add the worksheet at the end.
        sheet = DirectCast(workbook.Sheets.Add( _
            After:=workbook.Sheets(workbook.Sheets.Count), _
            Count:=1, _
            Type:=Excel.XlSheetType.xlWorksheet), _
                Excel.Worksheet)
        sheet.Name = sheet_name
    End If

    ' Add some data to individual cells.
    sheet.Cells(1, 1) = "A"
    sheet.Cells(1, 2) = "B"
    sheet.Cells(1, 3) = "C"

    ' Make that range of cells bold and red.
    Dim header_range As Excel.Range = sheet.Range("A1", _
        "C1")
    header_range.Font.Bold = True
    header_range.Font.Color = _
        System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
    header_range.Interior.Color = _
        System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Pink)

    ' Add some data to a range of cells.
    Dim values(,) As Integer = _
    { _
        {2, 4, 6}, _
        {3, 6, 9}, _
        {4, 8, 12}, _
        {5, 10, 15} _
    }
    Dim value_range As Excel.Range = sheet.Range("A2", "C5")
    value_range.Value2 = values

    ' Save the changes and close the workbook.
    workbook.Close(SaveChanges:=True)

    ' Close the Excel server.
    excel_app.Quit()

    MessageBox.Show("Done")
End Sub
 
First the code creates an Excel.Application object to control Excel. It makes that object visible so you can watch it work. Often you will not want to make the server visible.

Next the code opens a workbook. Most of the Open method's parameters are optional (things such as passwords and flags indicating that you want to open the file read-only) so only those that are needed are included in the call.

The code then calls the FindSheet method described shortly to see if the workbook contains a worksheet named after the current date. (Sorry about hard-coding in the date format. Normally I would use DateTime.Now.ToShortDate() to get an appropriate date but, for me at least, it would contain / characters, which are not allowed in worksheet name.)

If there is no worksheet with that name, the code creates one, adding it after the last worksheet, and sets the sheet's name.

Next the code sets the values of three cells individually. It then makes a Range representing those three cells and sets their Font.Bold, Color, and Interior.Color values.

The code then shows how to set worksheet values from an array. It creates a 2-dimensional array, makes a Range of the same size, and sets the Range's Value2 property to the array to set the cells' values.

Finally the code closes the workbook, saving the changes, and closes the Excel server.

The following code shows the FindSheet method.
 
' Return true if the workbook has a worksheet with this
' name.
Private Function FindSheet(ByVal workbook As Excel.Workbook, _
    ByVal sheet_name As String) As Excel.Worksheet
    For Each sheet As Excel.Worksheet In workbook.Sheets
        If (sheet.Name = sheet_name) Then Return sheet
    Next sheet

    Return Nothing
End Function
 
This method simply loops through the workbook's worksheets to see if it contains one with the given name.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated