Click here to Skip to main content
15,889,116 members
Articles / Desktop Programming / Windows Forms

Reading and writing an Excel file using VB.NET

Rate me:
Please Sign up or sign in to vote.
2.72/5 (19 votes)
20 Mar 2007CPOL 394.5K   5.8K   49   51
This code helps the user to interact with an Excel file using the OleDBDataProvider in VB.NET.

Screenshot - ExcelSheet.jpg

Introduction

This articles helps user to Insert, Update, Delete, and Select data in Excel files using the OLEDBDataProvider in VB.NET.

Here is the connection string to connect with Excel using OleDBDataProvider:

VB
Private Const connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Test.xls;Extended Properties=""Excel 8.0;HDR=YES;"""

Here is the code on the button click event to select and insert data in an Excel file:

VB
Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
    Dim pram As OleDbParameter
    Dim dr As DataRow
    Dim olecon As OleDbConnection
    Dim olecomm As OleDbCommand
    Dim olecomm1 As OleDbCommand
    Dim oleadpt As OleDbDataAdapter
    Dim ds As DataSet
    Try
        olecon = New OleDbConnection
        olecon.ConnectionString = connstring
        olecomm = New OleDbCommand
        olecomm.CommandText = _
           "Select FirstName, LastName, Age, Phone from [Sheet1$]"
        olecomm.Connection = olecon
        olecomm1 = New OleDbCommand
        olecomm1.CommandText = "Insert into [Sheet1$] " & _
            "(FirstName, LastName, Age, Phone) values " & _
            "(@FName, @LName, @Age, @Phone)"
        olecomm1.Connection = olecon
        pram = olecomm1.Parameters.Add("@FName", OleDbType.VarChar)
        pram.SourceColumn = "FirstName"
        pram = olecomm1.Parameters.Add("@LName", OleDbType.VarChar)
        pram.SourceColumn = "LastName"
        pram = olecomm1.Parameters.Add("@Age", OleDbType.VarChar)
        pram.SourceColumn = "Age"
        pram = olecomm1.Parameters.Add("@Phone", OleDbType.VarChar)
        pram.SourceColumn = "Phone"
        oleadpt = New OleDbDataAdapter(olecomm)
        ds = New DataSet
        olecon.Open()
        oleadpt.Fill(ds, "Sheet1")
        If IsNothing(ds) = False Then
            dr = ds.Tables(0).NewRow
            dr("FirstName") = "Raman"
            dr("LastName") = "Tayal"
            dr("Age") = 24
            dr("Phone") = 98989898
            ds.Tables(0).Rows.Add(dr)
            oleadpt = New OleDbDataAdapter
            oleadpt.InsertCommand = olecomm1
            Dim i As Integer = oleadpt.Update(ds, "Sheet1")
            MessageBox.Show(i & " row affected")
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        olecon.Close()
        olecon = Nothing
        olecomm = Nothing
        oleadpt = Nothing
        ds = Nothing
        dr = Nothing
        pram = Nothing
    End Try
End Sub

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMicrosoft.ACE.OLEDB.12.0 Pin
Member 1433303625-Apr-19 19:38
Member 1433303625-Apr-19 19:38 
Questionempty rows cells after importing data from excel 2000 Pin
Makumbisula16-Feb-15 19:40
Makumbisula16-Feb-15 19:40 
Questionhow to jump on 1st cell to 10th cell Pin
Member 1111752829-Sep-14 1:08
Member 1111752829-Sep-14 1:08 
QuestionThanks for detailed Pin
Mike Earl17-Jan-14 4:08
Mike Earl17-Jan-14 4:08 
Questionwrite data from one source excel file to destination excel file Pin
sanjivkp774-Dec-13 4:51
sanjivkp774-Dec-13 4:51 
VB
Private Const connstringSource As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\CIQExcel\UploadTest.xls;Extended Properties=""Excel 8.0;HDR=NO;IMEX=1;"""

Private Const connstringDestination As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\CIQExcel\Argo - Upload Template Design.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=NO;IMEX=1;"""

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Dim pram As OleDbParameter
    Dim dr As DataRow
    Dim ds As DataSet
    Dim ds1 As DataSet
    Dim olecon As OleDbConnection
    Dim olecon1 As OleDbConnection
    Dim olecomm As OleDbCommand
    Dim olecomm1 As OleDbCommand
    Dim olecomm2 As OleDbCommand
    Dim oleadpt As OleDbDataAdapter
    Dim oleadpt1 As OleDbDataAdapter
    Dim oleadpt2 As OleDbDataAdapter

    Try
        ''open Source file
        olecon = New OleDbConnection
        olecon.ConnectionString = connstringSource
        olecomm = New OleDbCommand
        olecomm.CommandText = "Select f2,f3 from [UploadTest$]"
        olecomm.Connection = olecon
        oleadpt = New OleDbDataAdapter(olecomm)
        ds = New DataSet
        olecon.Open()
        oleadpt.Fill(ds, "UploadTest")

        '' open Destination file
        olecon1 = New OleDbConnection
        olecon1.ConnectionString = connstringDestination
        olecomm1 = New OleDbCommand
        olecomm1.CommandText = "Select * from [Input$]"
        olecomm1.Connection = olecon1
        oleadpt1 = New OleDbDataAdapter(olecomm1)
        ds1 = New DataSet
        olecon1.Open()
        oleadpt1.Fill(ds1, "Input")

        olecomm2 = New OleDbCommand
        olecomm2.CommandText = "Update [Input$] set F2 = @F3"
        olecomm2.Connection = olecon1

        pram = olecomm2.Parameters.Add("@F3", OleDbType.VarChar)
        pram.SourceColumn = "F3"
        pram.SourceVersion = DataRowVersion.Original

        If IsNothing(ds) = False Then
            For j As Integer = 1 To ds.Tables(0).Rows.Count() - 1
                For k As Integer = 1 To ds.Tables(0).Columns().Count() - 1
                    dr = ds1.Tables(0).Rows(j - 1)
                    dr.BeginEdit()
                    dr(k) = ds.Tables(0).Rows(j).Item(k).ToString()
                    dr.EndEdit()
                Next
            Next

            oleadpt2 = New OleDbDataAdapter
            oleadpt2.UpdateCommand = olecomm2
            oleadpt2.Update(ds1, "Input")
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        olecon.Close()
        olecon1.Close()
        olecon = Nothing
        olecon1 = Nothing
        olecomm = Nothing
        olecomm1 = Nothing
        oleadpt = Nothing
        ds = Nothing
        ds1 = Nothing
        dr = Nothing
        pram = Nothing
    End Try
End Sub



In the above code, I am fetching the information from one source excel file and writing to destination excel file with column A as intact. I am writing from column B onwards. The destination dataset ds1 is populate as expected but my destination excel file is not updated with this dataset.

I am getting error as "Operation must be an updateable query"

let me know if you need sample files for reference.

Thanks in advance for your time and help.
GeneralThanks a Lot brother Pin
ravisankarvattikuti14-Mar-10 5:47
ravisankarvattikuti14-Mar-10 5:47 
GeneralRe: Thanks a Lot brother Pin
Raman Tayal15-Mar-10 6:54
Raman Tayal15-Mar-10 6:54 
Generalthanks Pin
bhavin123014-Sep-09 18:13
bhavin123014-Sep-09 18:13 
GeneralPlease clarify my question( urgent!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ) Pin
catchthedream31-Aug-09 1:43
catchthedream31-Aug-09 1:43 
QuestionPK??? Pin
Chris Maunderr22-Jul-09 22:10
Chris Maunderr22-Jul-09 22:10 
AnswerRe: PK??? Pin
Raman Tayal23-Jul-09 7:18
Raman Tayal23-Jul-09 7:18 
Questionmaking dictionary Pin
thaileang25-Jun-09 8:31
thaileang25-Jun-09 8:31 
QuestionExcel Upload Pin
WendellB4-May-09 8:47
WendellB4-May-09 8:47 
GeneralUpdate a shared excell file [modified] Pin
facu20yo19-Apr-09 3:57
facu20yo19-Apr-09 3:57 
Questionneed help...urgent! Pin
Member 430050816-Mar-09 18:11
Member 430050816-Mar-09 18:11 
AnswerRe: need help...urgent! Pin
Raman Tayal17-Mar-09 20:28
Raman Tayal17-Mar-09 20:28 
GeneralRe: need help...urgent! Pin
Member 430050820-Mar-09 19:13
Member 430050820-Mar-09 19:13 
Generalhelp Pin
pjacquez6816-Feb-09 7:06
pjacquez6816-Feb-09 7:06 
GeneralRe: help Pin
Raman Tayal16-Feb-09 20:50
Raman Tayal16-Feb-09 20:50 
Generali need your help bro, Pin
pjacquez6816-Feb-09 6:56
pjacquez6816-Feb-09 6:56 
Generaldelete Pin
pjacquez6816-Feb-09 4:15
pjacquez6816-Feb-09 4:15 
GeneralFrom Jacquez Pin
pjacquez6816-Feb-09 3:18
pjacquez6816-Feb-09 3:18 
GeneralGreat more code being posted THAT DOESN'T WORK OUT OF THE BOX. Pin
Member 389560127-Jan-09 14:00
Member 389560127-Jan-09 14:00 
GeneralRe: Great more code being posted THAT DOESN'T WORK OUT OF THE BOX. Pin
Raman Tayal28-Jan-09 5:04
Raman Tayal28-Jan-09 5:04 
GeneralRe: Great more code being posted THAT DOESN'T WORK OUT OF THE BOX. Pin
Member 389560128-Jan-09 5:28
Member 389560128-Jan-09 5:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.