Click here to Skip to main content
15,888,044 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I am using vb.net as the development language and sql2005 as backend.
I have to provide import facility in my application from excel.
There is loads of data in the excel sheet which need to be copied in the database

I have used sqlbulkcopy but had problems with it.

I have also used the direct connection to excel sheet using OLedbConnection but had problems with it too.

now I am using the third party ExcelReader
my code is:
 Dim sSheet As String = [" + SheetCombo.Text + "$];

 Dim stream1 As FileStream = File.Open(Filename, FileMode.Open, FileAccess.Read, FileShare.None)
Dim excelReader As IExcelDataReader

If stream1.Name.EndsWith(".xlsx") = True Then
' Reading from a OpenXml Excel file (2007 format; *.xlsx)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream1)
ElseIf stream1.Name.EndsWith(".xls") = True Then
' Reading from a binary Excel file ('97-2003 format; *.xls)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream1)
Else
excelReader = Nothing
MsgBox("Please Select a .xlsx or .xls file")
End If

excelReader.IsFirstRowAsColumnNames = True
Dim result As DataSet = excelReader.AsDataSet()
Me.DataGridView1.DataSource = result.Tables(0)

I am selecting the sheetnames from a SheetCombo which is a combobox.
Problem:Import was done but the date has 5 digits

Can any one help please.

I started with CSV conversion as _beauw_ told and went forward I guess in the right direction but now I am facing another problem

I saved the csv file and it had all the entries of the actual excel sheet but when I am using the below statement
VB
Dim objCmdSelect As New OleDbCommand("SELECT * FROM tempcsformat.csv", objConn)
            Dim objAdapter1 As New OleDbDataAdapter
            objAdapter1.SelectCommand = objCmdSelect
            objAdapter1.Fill(objDataset1, "test")
            objConn.Close()

I am facing problems with the date fields in my csv file.
Actually the date fields have mixed date format means dd/MM/yyyy and MM/dd/yyyy mainly.
I want to have a common dd/MM/yyyy format to entire date field.


I can read them as String but there should be some other solution for it.
If I use the above code to save the csv file records in database the dates which are not of currentculture means the current datetime format of the system are not considered as valid entries and all those dates that are not of current culture are not saved in the database..



Thanks alot bluesatish for your help and interest.
I saw this format function that can be used with csv file but I am not quiet sure where to use it,means I have used it in my select Statement of the csv file.

Dim objCmdSelect As New OleDbCommand("SELECT CId,SrNo,Format(Date,dd/MM/yyyy),Name," & aftnam & ",Format(DOB,dd/MM/yyyy),Age," & aftdob & " FROM tempcsformat.csv", objConn)
           Dim objAdapter1 As New OleDbDataAdapter
           objAdapter1.SelectCommand = objCmdSelect
           objAdapter1.Fill(objDataset1, "test")
           objConn.Close()

but I am getting an error value not passed for one or more parameter's.
Do anyone have any suggestions about where I am going wrong.
Posted
Updated 3-Jan-12 18:46pm
v6

http://codehill.com/2009/01/reading-excel-2003-and-2007-files-using-oledb/

have a look .
 
Share this answer
 
Comments
Vinay Indoria 3-Jan-12 2:35am    
I started with CSV conversion and went at a forward I guess in the right direction but now I am facing another problem

I saved the csv file and it had all the entries of the actual excel sheet but when I am using the below statement

Dim objCmdSelect As New OleDbCommand("SELECT * FROM tempcsformat.csv", objConn)
Dim objAdapter1 As New OleDbDataAdapter
objAdapter1.SelectCommand = objCmdSelect
objAdapter1.Fill(objDataset1, "test")
objConn.Close()


I am facing problems with the date fields in my file.
Actually the date fields have mixed date format means dd/MM/yyyy and MM/dd/yyyy mainly.
I want to have a common dd/MM/yyyy format to entire date field.
If I use the above code to save the csv file records in database the date's which are not of currentculture means the current datetime format of the system are not considered as valid entries and all those date's that are not of current culture are not save in the database..
Does any one have a solution for that.
Hi vinay,

Bulk Insert into SQL Server using SqlBulkCopy

I was recently tasked with a project at a company to update an SQL Server 2008 database with large amounts of data each day. The task at first seemed daunting due to the files exceeding well over 400,000 records and there were several that needed processing daily. I first tried LINQ to SQL, but with the amount of data, the inserts were slow performing to say the least. Then I remembered the SqlBulkCopy class. SqlBulkCopy lets you efficiently bulk load a SQL Server table with data from another source. The SqlBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance. For this example the file will contain roughly 1000 records, but this code can handle large amounts of data.
To begin with let’s create a table in SQL Server that will hold the data. Copy the following T-SQL into SQL Server to create your table:

SQL
CREATE TABLE [dbo].[Censis](
          [Suburb] [varchar](200) NULL,
          [NotStated] [int] NULL,
          [NotApplicable] [int] NULL,
          [Fishing] [int] NULL,
          [Mining] [int] NULL,
          [Manufacturing] [int] NULL,
          [Electricity] [int] NULL,
          [Construction] [int] NULL
) ON [PRIMARY]
GO

The table above will hold Censis data that is freely available to download in Australia.

The next item to do is create a console application that will bulk load the data. Open Visual Studio 2008 and choose File > New > Windows > Console Application.

Before moving on, to explain the code I have to work backwards and explain the final method that bulk loads data. SqlBulkCopy has a method called WriteToServer. One of the overloads of this method takes a DataTable as the parameter. Because a DataTable contains rows and columns, this seemed like a logical choice for the task I was facing.

Jumping back to the example we now know we need to create a DataTable that contains the information from the text file. The code below demonstrates how to do this:

C#
C#
 
DataTable dt = new DataTable();
string line = null;
int i = 0;
 
using (StreamReader sr = File.OpenText(@"c:\temp\table1.csv"))
{   
      while ((line = sr.ReadLine()) != null)
      {
            string[] data = line.Split(',');
            if (data.Length > 0)
            {
                  if (i == 0)
                  {
                  foreach (var item in data)
                  {
                        dt.Columns.Add(new DataColumn());
                  }
                  i++;
             }
             DataRow row = dt.NewRow();
             row.ItemArray = data;
             dt.Rows.Add(row);
             }
      }
}
VB
VB.NET
 
Dim dt As New DataTable()
Dim line As String = Nothing
Dim i As Integer = 0
 
Using sr As StreamReader = File.OpenText("c:\temp\table1.csv")
      line = sr.ReadLine()
      Do While line IsNot Nothing
             Dim data() As String = line.Split(","c)
                  If data.Length > 0 Then
                        If i = 0 Then
                         For Each item In data
                                    dt.Columns.Add(New DataColumn())
                         Next item
                         i += 1
                        End If
                   Dim row As DataRow = dt.NewRow()
                   row.ItemArray = data
                   dt.Rows.Add(row)
                  End If
            line = sr.ReadLine()
      Loop
End Using

In the code above, I created a DataTable that will store all the information from the csv file. The csv file resides in the C:\Temp directory. I am using a StreamReader object to open the file and read each line in the file. Each line is then split up into a string array. That string array will be assigned to each DataRow as the ItemArray value. This sets the values for the row through the array.

When the file has been read, the next thing to do is use the SqlBulkCopy class to insert the data into SQL Server. The following code demonstrates how to do this:

C#
C#
 
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsoleApplication3.Properties.Settings.daasConnectionString"].ConnectionString))
{
      cn.Open();
      using (SqlBulkCopy copy = new SqlBulkCopy(cn))
      {
            copy.ColumnMappings.Add(0, 0);
            copy.ColumnMappings.Add(1, 1);
            copy.ColumnMappings.Add(2, 2);
            copy.ColumnMappings.Add(3, 3);
            copy.ColumnMappings.Add(4, 4);
            copy.DestinationTableName = "Censis";
            copy.WriteToServer(dt);
      }
}  

VB
VB.NET
 
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConsoleApplication3.Properties.Settings.daasConnectionString").ConnectionString)
      cn.Open()
       Using copy As New SqlBulkCopy(cn)
             copy.ColumnMappings.Add(0, 0)
                  copy.ColumnMappings.Add(1, 1)
                  copy.ColumnMappings.Add(2, 2)
                  copy.ColumnMappings.Add(3, 3)
                  copy.ColumnMappings.Add(4, 4)
                  copy.DestinationTableName = "Censis"
                  copy.WriteToServer(dt)
       End Using
End Using


SqlBulkCopy uses ADO.NET to connect to a database to bulk load the data. I have created an SqlConnection object, and that object reference is used to create the SqlBulkCopy object. The DestinationTableName property references a table in the database where the data is to be loaded. A handy feature of SqlBulkCopy is the SqlBulkCopyColumnMappingCollection. Column mappings define the relationships between columns in the data source and columns in the destination. This is handy if the data source file has columns that don’t need to be inserted into the database. Column mappings can be set by an index, such as the example above, or they can be set by the name of the column. Using the index is handy when you’re working with files that contain no column names. Make sure both of your datatable and sqltable columns should be in a same order. Finally the data is sent to the database by running the WriteToServer method.

I suggest you to use sqibulkcopy() method to do this, its a very fastest than anyother insertion method.

Regards,
Bluesathish
 
Share this answer
 
Comments
Vinay Indoria 3-Jan-12 5:14am    
Thanks a lot for your suggestion bluesathish but I need to process some columns like I have to assign Id's and SrNo's for each record or line of csv file.
So cant use sqlbulkcopy,even I first though of SQlbulkcopy but then due to processing that need to be done on the csv file I have to read it line wise line and insert I record at a time.
Still
Dim dt As New DataTable()
Dim line As String = Nothing
Dim i As Integer = 0

Using sr As StreamReader = File.OpenText("c:\temp\table1.csv")
line = sr.ReadLine()
Do While line IsNot Nothing
Dim data() As String = line.Split(","c)
If data.Length > 0 Then
If i = 0 Then
For Each item In data
dt.Columns.Add(New DataColumn())
Next item
i += 1
End If
Dim row As DataRow = dt.NewRow()
row.ItemArray = data
dt.Rows.Add(row)
End If
line = sr.ReadLine()
Loop
End Using
The above fragment will help me with going through the csv file.
The problem now is the date field in my csv file which has mixed dates like dd/MM/yyyy and MM/dd/yyyy.
I need to change every date to dd/MM/yyyy,do you have any suggestion on this topic.Thank you very much for your interest in my question.
bluesathish 3-Jan-12 5:35am    
dear Vinay,
Check this link.,
http://stackoverflow.com/questions/203807/csv-date-format-vba
Vinay Indoria 4-Jan-12 0:42am    
Thanks alot bluesatish for your help and interest.
I saw this format function that can be used with csv file but I am not quiet sure where to use it,means I have used it in my select Statement of the csv file.

Dim objCmdSelect As New OleDbCommand("SELECT CId,SrNo,Format(Date,dd/MM/yyyy),Name," & aftnam & ",Format(DOB,dd/MM/yyyy),Age," & aftdob & " FROM tempcsformat.csv", objConn)
Dim objAdapter1 As New OleDbDataAdapter
objAdapter1.SelectCommand = objCmdSelect
objAdapter1.Fill(objDataset1, "test")
objConn.Close()

but I am getting an error value not passed for one or more parameter's.
Do you have any suggestions about where I am going wrong.
Sorry for late reply.
thanks once again.
bluesathish 4-Jan-12 1:26am    
Hi vinay,
I think you've fail to pass the aftnam/aftdob parameter's values at runtime. Debug your program and watch its runtime values.
Vinay Indoria 4-Jan-12 1:34am    
Hi bluesathish,
I checked them they had values in them.
Is my format function usage right?
Let us put everything together for better understanding

VB
Private Sub ImportToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ImportToolStripMenuItem.Click

       Try

           If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
               newimport(OpenFileDialog1.FileName, Application.StartupPath)
           End If

       Catch ex As Exception

           MsgBox(ex.ToString)
       End Try

   End Sub

This is the import on the menu
Sub newimport(ByVal filenam As String, ByVal startup As String)
       Try

           Dim Excel As New Microsoft.Office.Interop.Excel.Application
           Dim WorkBooks1 As Microsoft.Office.Interop.Excel.Workbooks
           Dim WorkBook1 As Microsoft.Office.Interop.Excel.Workbook
           WorkBooks1 = Excel.Workbooks

           WorkBook1 = WorkBooks1.Open(filenam)
           Dim totfilenam = startup & "\tempcsformat.csv"

           ' XlFileFormat.xlWorkbookDefault = 51 - this is correct, although a lot of forums recommend

           WorkBook1.SaveAs(Filename:=totfilenam,FileFormat:=XlFileFormat.xlCSV)

           'CLEANUP

           WorkBook1.Save() 'trying to find a way to get this to close without a prompt
           WorkBook1.Close(False)
           WorkBooks1.Close()
           Excel.Quit()

           System.Runtime.InteropServices.Marshal.ReleaseComObject(WorkBook1)
           System.Runtime.InteropServices.Marshal.ReleaseComObject(WorkBooks1)
           System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)

           WorkBook1 = Nothing
           WorkBooks1 = Nothing
           Excel = Nothing
           SaveCSV(totfilenam.Trim, startup)

       Catch ex As Exception
           MsgBox(ex.ToString())
       End Try


   End Sub

I am keeping the temporary csv file in the default startup of the project.
I am using save as function,there are other ways to create a csv out of excel but SaveAs worked for me.

 Sub SaveCSV(ByVal totstartup As String, ByVal startup As String)
        Try

           'You can read entire file using Stream reader like below

            Dim dt As New System.Data.DataTable
            Dim line As String = Nothing
            Dim i As Integer = 0

            Using sr As StreamReader = File.OpenText(totstartup)
                line = sr.ReadLine()
                Do While line IsNot Nothing
                    Dim data() As String = line.Split(","c)
                    If data.Length > 0 Then
                        If i = 0 Then
                            For Each item In data
                                dt.Columns.Add(New DataColumn())
                            Next item
                            i += 1
                        End If
                        Dim row As DataRow = dt.NewRow()
                        row.ItemArray = data
                        dt.Rows.Add(row)
                       
                    End If
                    line = sr.ReadLine()
                Loop
            End Using

            'Then we can loop through the dt datatable and save the data in database

            ''Or you can go for the fetching using datasource
            ' Opening the file

            Dim sConnectionString As String ="provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & startup & ";Extended Properties=""text;HDR=Yes;FMT=Delimited"""
            Dim objConn As New OleDbConnection(sConnectionString)
            Dim objDataset1 As New DataSet
            objConn.Close()
            objConn.Open()

           'aftnam and aftdob consists of other column names of my tables.         

            Dim objCmdSelect As New OleDbCommand("SELECT CId,SrNo,Format(Date,""dd/MM/yyyy""),Name," & aftnam & ",Format(DOB,""dd/MM/yyyy""),Age," & aftdob & " FROM tempcsformat.csv", objConn)
            Dim objAdapter1 As New OleDbDataAdapter
            objAdapter1.SelectCommand = objCmdSelect
            objAdapter1.Fill(objDataset1, "test")
            objConn.Close()
            
            'You can then loop through the objDataset1.rows to get the data of your csv file like

for each dr in objDataset1.Table(0).rows

'your code of saving the data.

Next
            MsgBox("Imported Successfully")

' Deleteing the temporary csv file

            If System.IO.File.Exists(totstartup) = True Then
                System.IO.File.Delete(totstartup)
            End If

        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub
 
Share this answer
 
Comments
RaviRanjanKr 4-Jan-12 3:32am    
A suggestion :- you can use Have a question or Comment button to drop your message and to get Immediate response instead of posting as answer.
Vinay Indoria 4-Jan-12 5:31am    
Hi RaviShankr,
This is the answer,I combined the various suggestions that _blueaw_ and bluesathish and completed the task that I have to achieve and for a single reference I put my work as an answer.
Thank you for your suggestion

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900