Click here to Skip to main content
15,888,984 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

 
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 
GeneralRe: Great more code being posted THAT DOESN'T WORK OUT OF THE BOX. Pin
Raman Tayal28-Jan-09 18:14
Raman Tayal28-Jan-09 18:14 
GeneralRe: Great more code being posted THAT DOESN'T WORK OUT OF THE BOX. Pin
Alejandro Marín20-Oct-09 6:42
Alejandro Marín20-Oct-09 6:42 
GeneralRe: Great more code being posted THAT DOESN'T WORK OUT OF THE BOX. Pin
Raman Tayal21-Oct-09 7:47
Raman Tayal21-Oct-09 7:47 
GeneralMy vote of 1 Pin
Member 389560127-Jan-09 13:59
Member 389560127-Jan-09 13:59 
Questionit takes much time to insert nearly 2000 rows from dataset to Excel. Pin
Uemsh19-Jun-08 4:59
Uemsh19-Jun-08 4:59 
Please reply me ASAP. Thanks

Hi, I used your code for select, insert data in excel.
I implemented it and runs successfully.
If number of rows in dataset is less, i.e. aroud 100 then it works fast. But I have more than 2000 rows in my dataset and the mathod oleDataAdepter.InsertCommand = cmdInsertCommand is taking too much time to write thode data in excel. it takes around 10 minutes.

whereas Time taken when I manually loop throw my dataset and wrte data using wrksheet.Range("A" & rowNum).Value = dsPlan.Tables(0).Rows(i)("mphId") is arond 3-4 minutes.

I thought your code will work fast as it does not involves looping. and use Inser, Update methods of oleDBComman. But I dont know why it takes much time.

Here is my method which accepts dataset as input parameter which contains data selected from database tables of SQL Server. I want to write those data in excel sheet.

Private Sub WriteVegUnitData(ByVal ds As DataSet)
'Parameter dataset "ds" which contains data selected from SQL Server

Dim olecon As OleDbConnection
Dim oleSelectCmd As OleDbCommand
Dim oleInsertCmd As OleDbCommand
Dim oleadpt As OleDbDataAdapter
Dim dsExcel As DataSet
Dim pram As OleDbParameter
Dim drExcel As DataRow

Try
olecon = New OleDbConnection
olecon.ConnectionString = connstring

oleSelectCmd = New OleDbCommand


oleSelectCmd.CommandText = "Select ID, VEGWORKPLANID, ACTION, VEGSPECIESNAME, VEGSIZENAME, ACTIONDETAILNAME, ACTIONDETAILDISTANCE, VEGSPECIESGROWTHTYPEID, MAPPING_ID, NEW_REC_ID, DEL from [VEGUNIT$]"
oleSelectCmd.Connection = olecon

oleInsertCmd = New OleDbCommand
oleInsertCmd.CommandText = "Insert into [VEGUNIT$] " & _
"(ID, VEGWORKPLANID, ACTION, VEGSPECIESNAME, VEGSIZENAME, ACTIONDETAILNAME, ACTIONDETAILDISTANCE, VEGSPECIESGROWTHTYPEID, MAPPING_ID, NEW_REC_ID, DEL) values (@ID, @VEGWORKPLANID, @ACTION, @VEGSPECIESNAME, @VEGSIZENAME, @ACTIONDETAILNAME, @ACTIONDETAILDISTANCE, @VEGSPECIESGROWTHTYPEID, @MAPPING_ID, @NEW_REC_ID, @DEL)"
oleInsertCmd.Connection = olecon

pram = oleInsertCmd.Parameters.Add("@ID", OleDbType.VarChar)
pram.SourceColumn = "ID"
pram = oleInsertCmd.Parameters.Add("@VEGWORKPLANID", OleDbType.VarChar)
pram.SourceColumn = "VEGWORKPLANID"
pram = oleInsertCmd.Parameters.Add("@ACTION", OleDbType.VarChar)
pram.SourceColumn = "ACTION"
pram = oleInsertCmd.Parameters.Add("@VEGSPECIESNAME", OleDbType.VarChar)
pram.SourceColumn = "VEGSPECIESNAME"
pram = oleInsertCmd.Parameters.Add("@VEGSIZENAME", OleDbType.VarChar)
pram.SourceColumn = "VEGSIZENAME"
pram = oleInsertCmd.Parameters.Add("@ACTIONDETAILNAME", OleDbType.VarChar)
pram.SourceColumn = "ACTIONDETAILNAME"
pram = oleInsertCmd.Parameters.Add("@ACTIONDETAILDISTANCE", OleDbType.VarChar)
pram.SourceColumn = "ACTIONDETAILDISTANCE"
pram = oleInsertCmd.Parameters.Add("@VEGSPECIESGROWTHTYPEID", OleDbType.VarChar)
pram.SourceColumn = "VEGSPECIESGROWTHTYPEID"
pram = oleInsertCmd.Parameters.Add("@MAPPING_ID", OleDbType.VarChar)
pram.SourceColumn = "MAPPING_ID"
pram = oleInsertCmd.Parameters.Add("@NEW_REC_ID", OleDbType.VarChar)
pram.SourceColumn = "NEW_REC_ID"
pram = oleInsertCmd.Parameters.Add("@DEL", OleDbType.VarChar)
pram.SourceColumn = "DEL"

oleadpt = New OleDbDataAdapter(oleSelectCmd)
dsExcel = New DataSet
olecon.Open()
oleadpt.Fill(dsExcel)

If IsNothing(dsExcel) = False Then
For Each dr As DataRow In ds.Tables(0).Rows
drExcel = dsExcel.Tables(0).NewRow
drExcel("ID") = dr("strID")
drExcel("VEGWORKPLANID") = dr("wpdWphID")
drExcel("ACTION") = dr("wpdPruneRemove")
drExcel("VEGSPECIESNAME") = dr("vspSpeciesDesc")
drExcel("VEGSIZENAME") = dr("vszSizeDesc")
drExcel("ACTIONDETAILNAME") = dr("vacActionDesc")
drExcel("ACTIONDETAILDISTANCE") = dr("vdsDistanceDesc")
drExcel("VEGSPECIESGROWTHTYPEID") = dr("wpdGrowthTypeId")
drExcel("MAPPING_ID") = dr("wpdID")
drExcel("NEW_REC_ID") = "A"
drExcel("DEL") = dr("dlt")
dsExcel.Tables(0).Rows.Add(drExcel)
Next

oleadpt = New OleDbDataAdapter
oleadpt.InsertCommand = oleInsertCmd

Dim i As Integer = oleadpt.Update(dsExcel)
MessageBox.Show(i & " row affected")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
olecon.Close()
olecon = Nothing
oleSelectCmd = Nothing
oleInsertCmd = Nothing
oleadpt = Nothing
dsExcel = Nothing
drExcel = Nothing
pram = Nothing
End Try
End Sub
AnswerRe: it takes much time to insert nearly 2000 rows from dataset to Excel. Pin
Raman Tayal23-Jun-08 19:35
Raman Tayal23-Jun-08 19:35 
GeneralRe: it takes much time to insert nearly 2000 rows from dataset to Excel. Pin
Uemsh8-Jul-08 11:44
Uemsh8-Jul-08 11:44 
Questionhow can I insert these dataset into my databse Pin
lama819858-May-08 2:50
lama819858-May-08 2:50 
GeneralRead Excel (xls) file which is present on internet (by using VB.Net) Pin
kirangh5-May-08 21:45
kirangh5-May-08 21:45 
GeneralRe: Read Excel (xls) file which is present on internet (by using VB.Net) Pin
SCL_896-Aug-09 22:11
SCL_896-Aug-09 22:11 
GeneralThird party components Pin
FilipKrnjic28-Apr-08 4:04
FilipKrnjic28-Apr-08 4:04 
QuestionError on reading excel file Pin
neelu777930-Oct-07 23:11
neelu777930-Oct-07 23:11 
AnswerRe: Error on reading excel file Pin
Raman Tayal31-Oct-07 18:03
Raman Tayal31-Oct-07 18:03 
GeneralRe: Error on reading excel file [modified] Pin
neelu77791-Nov-07 7:01
neelu77791-Nov-07 7:01 
Generalhelp me Pin
slayer_stb30-Oct-07 18:24
slayer_stb30-Oct-07 18:24 
GeneralRe: help me Pin
Raman Tayal31-Oct-07 18:34
Raman Tayal31-Oct-07 18:34 
GeneralRe: help me Pin
Mick_wijaya30-Jul-08 21:50
Mick_wijaya30-Jul-08 21:50 
Generalpassword protected excel Pin
kenchua525-Jul-07 20:33
kenchua525-Jul-07 20:33 
GeneralRe: password protected excel Pin
privacy space29-Feb-08 3:04
privacy space29-Feb-08 3:04 
GeneralDelete and update Pin
amu rath8-May-07 0:48
amu rath8-May-07 0:48 
GeneralAbout Excel Pin
G.NaaNee12-Apr-07 2:22
G.NaaNee12-Apr-07 2:22 
GeneralRe: About Excel Pin
Raman Tayal12-Apr-07 6:06
Raman Tayal12-Apr-07 6:06 

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.