473,418 Members | 2,067 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,418 software developers and data experts.

import excel sheet into a sql server table

TG
hi!

I am trying to create a sql server table from an excel sheet.

Here is the code I have:

'This procedure the xlsx file and dumps it to a table in SQL Server

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button5.Click

'CreateTable()
'GenerateQueryFromDataGridView(DataGridView1, "Spambank",
"temp_spaminfo")

Dim excelConnection As System.Data.OleDb.OleDbConnection = New
System.Data.OleDb.OleDbConnection("Provider=Micros oft.Jet.OLEDB.
4.0;Data Source= C:\exporteddata.xlsx;Extended Properties=Excel
8.0;HDR=YES;")

'Dim sExcelConnectionString As String =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & (sExcelFileName) &
";Extended Properties=""Excel 8.0;HDR=YES;"""

excelConnection.Open()
Dim excelCommand As New System.Data.OleDb.OleDbCommand("SELECT
* INTO [ODBC; Driver={SQL Server};Server=" & lstServers.SelectedValue
& ";Database=SpamBank;Trusted_Connection=yes].[temp_spaminfo] FROM
[Sheet1$];", excelConnection)

Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As New DataSet

conn = New SqlConnection("Data Source=" &
lstServers.SelectedValue & ";Initial Catalog=Spambank;Integrated
Security=SSPI")
cmd = New SqlCommand("SELECT * FROM sys.objects WHERE
object_id = OBJECT_ID(N'temp_spaminfo')", conn)

da = New SqlDataAdapter(cmd)
da.Fill(ds)

If (ds.Tables(0).Rows.Count 0) Then
MessageBox.Show("Table succesfully created in [" &
lstServers.SelectedValue & "].dbo.Spambank")
Else
MessageBox.Show("The table doesn't exist in Spambank
database")
End If

End Sub

Unfortunately I am getting an error message "Could not find
installable ISAM" at this point
excelConnection.Open()
Your help will be greatly appreciate it.

Thanks

Tammy
Jun 27 '08 #1
7 12027
Hi Tammy,

Here is a method which works for me for reading data from Excel and
writing it to Sql Server. Note: More times than not, you have to prep
the data in the Excel sheet - meaning - eliminating unused rows at then
end of the dataset in Excel, eliminating unused columns also at the end
of the dataset in Excel, making sure that the datatypes in each column
in the Excel sheet are valid (General format usually works OK but
sometimes have to format date fields as dates explicitly, text fields as
text, explicityly, numeric fields as numbers excplicitly). The note
doesn't really have anything to do with "Missing ISAM", but just
something to be aware of.

-----------------------------------
Private Sub WriteDataToSqlServerFromExcel()
Dim da As OleDbDataAdapter, conn As OleDbConnection
conn = New OleDbConnection
conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data
source=C:\someDir\test1.xls;Extended Properties=Excel 8.0"

da = New OleDbDataAdapter
da.SelectCommand = New OleDbCommand
da.SelectCommand.Connection = conn
da.SelectCommand.CommandText = "Select * From [" Sheet1$]"

da.Fill(ds1, "Sheet1OLE")

Dim daS As New SqlDataAdapter, connS As New SqlConnection

connS.ConnectionString = "Data Source=MyServer;Initial
Catalog=MyDB;Integrated Security=True"

daS.SelectCommand = New SqlCommand
daS.SelectCommand.Connection = connS
daS.InsertCommand = New SqlCommand
daS.InsertCommand.Connection = connS

daS.SelectCommand.CommandText = "Select * From Sheet1DBTbl"
daS.Fill(ds1, "sht1DBtbl")

daS.InsertCommand.Parameters.Add("@fdl1", SqlDbType.VarChar, 50, "fld1")
daS.InsertCommand.Parameters.Add("@fdl2", SqlDbType.VarChar, 50, "fld2")
daS.InsertCommand.Parameters.Add("@fdl3", SqlDbType.VarChar, 50, "fld3")
...
daS.InsertCommand.CommandText = "Insert Into Sheet1DBTbl Select @fld1,
@fld2, @fld3, ..."

Dim reader As DataTableReader = ds1.Tables("Sheet1OLE").CreateDataReader
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
daS.Update(ds1, "sht1DBtbl")

End Sub

-------------------------------------------

There are 2 caveats here - 1) Sheet1DBTbl is an existing table on the
server DB (if there isn't one there - you need to create it either at
the server or from code). 2) However many fields there are in the Excel
sheet (and in the table on the sql server - which must match the same
number of columns there are in the Excel sheet and the Server DB table)
-- you have to add the same number of parameters to the DataAdapter
InsertCommand. So the first half of the procedure above reads the data
from Excel into a memory table in the dataset (ds1) and the 2nd half of
the procedure writes the data from the OLE table to the Sql Server table
using a dataReader object.

One more note:

ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)

(Except for the tableName -- use your own table name) this is the
correct syntax -- VB2005.

Rich

*** Sent via Developersdex http://www.developersdex.com ***
Jun 27 '08 #2
TG
On May 27, 4:58*pm, Rich P <rpng...@aol.comwrote:
Hi Tammy,

Here is a method which works for me for reading data from Excel and
writing it to Sql Server. *Note: *More times than not, you have to prep
the data in the Excel sheet - meaning - eliminating unused rows at then
end of the dataset in Excel, eliminating unused columns also at the end
of the dataset in Excel, making sure that the datatypes in each column
in the Excel sheet are valid (General format usually works OK but
sometimes have to format date fields as dates explicitly, text fields as
text, explicityly, numeric fields as numbers excplicitly). *The note
doesn't really have anything to do with "Missing ISAM", but just
something to be aware of.

-----------------------------------
Private Sub WriteDataToSqlServerFromExcel()
Dim da As OleDbDataAdapter, conn As OleDbConnection
conn = New OleDbConnection
conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data
source=C:\someDir\test1.xls;Extended Properties=Excel 8.0"

da = New OleDbDataAdapter
da.SelectCommand = New OleDbCommand
da.SelectCommand.Connection = conn
da.SelectCommand.CommandText = "Select * From [" Sheet1$]"

da.Fill(ds1, "Sheet1OLE")

Dim daS As New SqlDataAdapter, connS As New SqlConnection

connS.ConnectionString = "Data Source=MyServer;Initial
Catalog=MyDB;Integrated Security=True"

daS.SelectCommand = New SqlCommand
daS.SelectCommand.Connection = connS
daS.InsertCommand = New SqlCommand
daS.InsertCommand.Connection = connS

daS.SelectCommand.CommandText = "Select * From Sheet1DBTbl"
daS.Fill(ds1, "sht1DBtbl")

daS.InsertCommand.Parameters.Add("@fdl1", SqlDbType.VarChar, 50, "fld1")
daS.InsertCommand.Parameters.Add("@fdl2", SqlDbType.VarChar, 50, "fld2")
daS.InsertCommand.Parameters.Add("@fdl3", SqlDbType.VarChar, 50, "fld3")
..
daS.InsertCommand.CommandText = "Insert Into Sheet1DBTbl Select @fld1,
@fld2, @fld3, ..."

Dim reader As DataTableReader = ds1.Tables("Sheet1OLE").CreateDataReader
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
daS.Update(ds1, "sht1DBtbl")

End Sub

-------------------------------------------

There are 2 caveats here - 1) Sheet1DBTbl is an existing table on the
server DB (if there isn't one there - you need to create it either at
the server or from code). *2) However many fields there are in the Excel
sheet (and in the table on the sql server - which must match the same
number of columns there are in the Excel sheet and the Server DB table)
-- you have to add the same number of parameters to the DataAdapter
InsertCommand. *So the first half of the procedure above reads the data
from Excel into a memory table in the dataset (ds1) and the 2nd half of
the procedure writes the data from the OLE table to the Sql Server table
using a dataReader object.

One more note:

ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)

(Except for the tableName -- use your own table name) this is the
correct syntax -- VB2005.

Rich

*** Sent via Developersdexhttp://www.developersdex.com***

Hi Rich!!

Thank you so much for yur reply!!!

I understand what you are doing but in my case I have an extra
problem. Sometimes the Excel file will have a minimum of 4 columns
(this ones will always be present) and then 5 other columns that might
all show up or not dependinf if the user select the checkbox. How do I
reflect that?

I cannot create a table manually in sql server, because i don't know
how many the user wants to see.

how can i do this with vb code?

thanks a lot for all ur time!!!!

regards,
Tammy
Jun 27 '08 #3
"TG" wrote:
-----------------------------------
Private Sub WriteDataToSqlServerFromExcel()
Dim da As OleDbDataAdapter, conn As OleDbConnection
conn = New OleDbConnection
conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data
source=C:\someDir\test1.xls;Extended Properties=Excel 8.0"

For .xlsx files you need a different connection string. See this link:

http://www.connectionstrings.com/?carrier=excel2007

--
urkec
Jun 27 '08 #4
Hi,

You could try to use some third party component for exporting data to
Excel file. I recommend you to use GemBox.Spreadsheet -- here is the
example of importing/exporting data from DataTable to Excel files
(XLS, XLSX, CSV): http://www.gemboxsoftware.com/LDataTable.htm.

If you want to use free component, note that there is free version of
GemBox.Spreadsheet available -- you can even use it in your commercial
applications. Free version comes with 150 rows limit. You can find
free version here: http://www.gemboxsoftware.com/GBSpreadsheetFree.htm.

Mario
GemBox Software
--
GemBox.Spreadsheet for .NET - Easily read and write Excel (XLS, XLSX
or CSV)
or export to HTML files from your .NET apps. See
http://www.gemboxsoftware.com/GBSpreadsheet.htm
--
On May 28, 2:54 am, TG <jtam...@yahoo.comwrote:
On May 27, 4:58 pm, Rich P <rpng...@aol.comwrote:
Hi Tammy,
Here is a method which works for me for reading data from Excel and
writing it to Sql Server. Note: More times than not, you have to prep
the data in the Excel sheet - meaning - eliminating unused rows at then
end of the dataset in Excel, eliminating unused columns also at the end
of the dataset in Excel, making sure that the datatypes in each column
in the Excel sheet are valid (General format usually works OK but
sometimes have to format date fields as dates explicitly, text fields as
text, explicityly, numeric fields as numbers excplicitly). The note
doesn't really have anything to do with "Missing ISAM", but just
something to be aware of.
-----------------------------------
Private Sub WriteDataToSqlServerFromExcel()
Dim da As OleDbDataAdapter, conn As OleDbConnection
conn = New OleDbConnection
conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data
source=C:\someDir\test1.xls;Extended Properties=Excel 8.0"
da = New OleDbDataAdapter
da.SelectCommand = New OleDbCommand
da.SelectCommand.Connection = conn
da.SelectCommand.CommandText = "Select * From [" Sheet1$]"
da.Fill(ds1, "Sheet1OLE")
Dim daS As New SqlDataAdapter, connS As New SqlConnection
connS.ConnectionString = "Data Source=MyServer;Initial
Catalog=MyDB;Integrated Security=True"
daS.SelectCommand = New SqlCommand
daS.SelectCommand.Connection = connS
daS.InsertCommand = New SqlCommand
daS.InsertCommand.Connection = connS
daS.SelectCommand.CommandText = "Select * From Sheet1DBTbl"
daS.Fill(ds1, "sht1DBtbl")
daS.InsertCommand.Parameters.Add("@fdl1", SqlDbType.VarChar, 50, "fld1")
daS.InsertCommand.Parameters.Add("@fdl2", SqlDbType.VarChar, 50, "fld2")
daS.InsertCommand.Parameters.Add("@fdl3", SqlDbType.VarChar, 50, "fld3")
..
daS.InsertCommand.CommandText = "Insert Into Sheet1DBTbl Select @fld1,
@fld2, @fld3, ..."
Dim reader As DataTableReader = ds1.Tables("Sheet1OLE").CreateDataReader
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
daS.Update(ds1, "sht1DBtbl")
End Sub
-------------------------------------------
There are 2 caveats here - 1) Sheet1DBTbl is an existing table on the
server DB (if there isn't one there - you need to create it either at
the server or from code). 2) However many fields there are in the Excel
sheet (and in the table on the sql server - which must match the same
number of columns there are in the Excel sheet and the Server DB table)
-- you have to add the same number of parameters to the DataAdapter
InsertCommand. So the first half of the procedure above reads the data
from Excel into a memory table in the dataset (ds1) and the 2nd half of
the procedure writes the data from the OLE table to the Sql Server table
using a dataReader object.
One more note:
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
(Except for the tableName -- use your own table name) this is the
correct syntax -- VB2005.
Rich
*** Sent via Developersdexhttp://www.developersdex.com***

Hi Rich!!

Thank you so much for yur reply!!!

I understand what you are doing but in my case I have an extra
problem. Sometimes the Excel file will have a minimum of 4 columns
(this ones will always be present) and then 5 other columns that might
all show up or not dependinf if the user select the checkbox. How do I
reflect that?

I cannot create a table manually in sql server, because i don't know
how many the user wants to see.

how can i do this with vb code?

thanks a lot for all ur time!!!!

regards,

Tammy
Jun 27 '08 #5
TG
On May 28, 8:05*am, ma...@gemboxsoftware.com wrote:
Hi,

You could try to use some third party component for exporting data to
Excel file. I recommend you to use GemBox.Spreadsheet -- here is the
example of importing/exporting data from DataTable *to Excel files
(XLS, XLSX, CSV):http://www.gemboxsoftware.com/LDataTable.htm.

If you want to use free component, note that there is free version of
GemBox.Spreadsheet available -- you can even use it in your commercial
applications. Free version comes with 150 rows limit. You can find
free version here:http://www.gemboxsoftware.com/GBSpreadsheetFree.htm.

Mario
GemBox Software
--
GemBox.Spreadsheet for .NET - Easily read and write Excel (XLS, XLSX
or CSV)
or export to HTML files from your .NET apps. Seehttp://www.gemboxsoftware.com/GBSpreadsheet.htm
--

On May 28, 2:54 am, TG <jtam...@yahoo.comwrote:
On May 27, 4:58 pm, Rich P <rpng...@aol.comwrote:
Hi Tammy,
Here is a method which works for me for reading data from Excel and
writing it to Sql Server. *Note: *More times than not, you have toprep
the data in the Excel sheet - meaning - eliminating unused rows at then
end of the dataset in Excel, eliminating unused columns also at the end
of the dataset in Excel, making sure that the datatypes in each column
in the Excel sheet are valid (General format usually works OK but
sometimes have to format date fields as dates explicitly, text fields as
text, explicityly, numeric fields as numbers excplicitly). *The note
doesn't really have anything to do with "Missing ISAM", but just
something to be aware of.
-----------------------------------
Private Sub WriteDataToSqlServerFromExcel()
Dim da As OleDbDataAdapter, conn As OleDbConnection
conn = New OleDbConnection
conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data
source=C:\someDir\test1.xls;Extended Properties=Excel 8.0"
da = New OleDbDataAdapter
da.SelectCommand = New OleDbCommand
da.SelectCommand.Connection = conn
da.SelectCommand.CommandText = "Select * From [" Sheet1$]"
da.Fill(ds1, "Sheet1OLE")
Dim daS As New SqlDataAdapter, connS As New SqlConnection
connS.ConnectionString = "Data Source=MyServer;Initial
Catalog=MyDB;Integrated Security=True"
daS.SelectCommand = New SqlCommand
daS.SelectCommand.Connection = connS
daS.InsertCommand = New SqlCommand
daS.InsertCommand.Connection = connS
daS.SelectCommand.CommandText = "Select * From Sheet1DBTbl"
daS.Fill(ds1, "sht1DBtbl")
daS.InsertCommand.Parameters.Add("@fdl1", SqlDbType.VarChar, 50, "fld1")
daS.InsertCommand.Parameters.Add("@fdl2", SqlDbType.VarChar, 50, "fld2")
daS.InsertCommand.Parameters.Add("@fdl3", SqlDbType.VarChar, 50, "fld3")
..
daS.InsertCommand.CommandText = "Insert Into Sheet1DBTbl Select @fld1,
@fld2, @fld3, ..."
Dim reader As DataTableReader = ds1.Tables("Sheet1OLE").CreateDataReader
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
daS.Update(ds1, "sht1DBtbl")
End Sub
-------------------------------------------
There are 2 caveats here - 1) Sheet1DBTbl is an existing table on the
server DB (if there isn't one there - you need to create it either at
the server or from code). *2) However many fields there are in the Excel
sheet (and in the table on the sql server - which must match the same
number of columns there are in the Excel sheet and the Server DB table)
-- you have to add the same number of parameters to the DataAdapter
InsertCommand. *So the first half of the procedure above reads the data
from Excel into a memory table in the dataset (ds1) and the 2nd half of
the procedure writes the data from the OLE table to the Sql Server table
using a dataReader object.
One more note:
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
(Except for the tableName -- use your own table name) this is the
correct syntax -- VB2005.
Rich
*** Sent via Developersdexhttp://www.developersdex.com***
Hi Rich!!
Thank you so much for yur reply!!!
I understand what you are doing but in my case I have an extra
problem. Sometimes the Excel file will have a minimum of 4 columns
(this ones will always be present) and then 5 other columns that might
all show up or not dependinf if the user select the checkbox. How do I
reflect that?
I cannot create a table manually in sql server, because i don't know
how many the user wants to see.
how can i do this with vb code?
thanks a lot for all ur time!!!!
regards,
Tammy- Hide quoted text -

- Show quoted text -


Thank you all for taking time to answer me.

Mario,

I do not need to export data to Excel.That part of my code works
perfect as it is.

Urkec and Rich,
My problem is importing back into a SQL SERVER TABLE that needs to be
created based on the EXCEL COLUMNS The Excel columns can vary from
only 4 to 9 and everything in between depending on what the user
selects in the code below.
HERE IS WHERE THE USER SELECTS WHICH FIELDS WILL BE SHOWN IN THE
DATAGRIDVIEW: (THIS WORKS PERFECT)

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click

Cursor.Current = System.Windows.Forms.Cursors.WaitCursor

Dim cn As New SqlConnection("Data Source=" &
lstServers.SelectedValue & ";Initial Catalog=" &
lstDatabases.SelectedValue & ";Integrated Security=SSPI")
Dim cmd As New SqlCommand("usp_DR_Spam_BB_Search_get_recs",
cn)
cmd.CommandTimeout = 0
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Matter",
lstDatabases.SelectedItem)
cmd.Parameters.AddWithValue("@FileSet",
lstFileSets.SelectedItem)

cn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ds As New DataSet()
Dim dt As New DataTable("Table1")
ds.Tables.Add(dt)
ds.Load(reader, LoadOption.PreserveChanges, ds.Tables(0))
DataGridView1.Font = New Font("SansSerif", 8.25,
FontStyle.Regular)
DataGridView1.DataSource = ds.Tables(0)

If DataGridView1.Rows.Count 0 Then

If CheckBox1.CheckState = True Then

DataGridView1.Columns("Last Name").Visible = True
ElseIf CheckBox1.CheckState = False Then

DataGridView1.Columns("Last Name").Visible = False

End If

If CheckBox2.CheckState = True Then

DataGridView1.Columns("First Name").Visible = True

ElseIf CheckBox2.CheckState = False Then

DataGridView1.Columns("First Name").Visible = False

End If

If CheckBox3.CheckState = True Then

DataGridView1.Columns("Domain").Visible = True

ElseIf CheckBox3.CheckState = False Then

DataGridView1.Columns("Domain").Visible = False

End If

If CheckBox4.CheckState = True Then

DataGridView1.Columns("Email").Visible = True

ElseIf CheckBox4.CheckState = False Then

DataGridView1.Columns("Email").Visible = False

End If

If CheckBox5.CheckState = True Then

DataGridView1.Columns("Subject").Visible = True

ElseIf CheckBox5.CheckState = False Then

DataGridView1.Columns("Subject").Visible = False

End If

Else

MessageBox.Show("There are no records using the fileset
selected, please try with a different fileset")

End If
Dim rowNumber As Integer = 1
For Each row As DataGridViewRow In DataGridView1.Rows
If row.IsNewRow Then Continue For
row.HeaderCell.Value = rowNumber.ToString
rowNumber = rowNumber + 1
Next
DataGridView1.AutoResizeRowHeadersWidth(DataGridVi ewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)

Cursor.Current = System.Windows.Forms.Cursors.Default

'cmd.Connection.Close()

End Sub

================================================== ================================================== =================================

HERE IS WHERE THE USER CAN EXPORT TO XLSX (THIS WORKS PERFECT)
Private Sub exportExcel(ByVal grdView As DataGridView, ByVal fileName
As String, _
ByVal fileExtension As String, ByVal filePath As String)

' Choose the path, name, and extension for the Excel file
Dim myFile As String = filePath & "\" & fileName &
fileExtension
' Open the file and write the headers
Dim fs As New IO.StreamWriter(myFile, False)
fs.WriteLine("<?xml version=""1.0""?>")
fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")
fs.WriteLine("<ss:Workbook xmlns:ss=""urn:schemas-microsoft-
com:office:spreadsheet"">")

' Create the styles for the worksheet
fs.WriteLine(" <ss:Styles>")
' Style for the column headers
fs.WriteLine(" <ss:Style ss:ID=""1"">")
fs.WriteLine(" <ss:Font ss:Bold=""1""/>")
fs.WriteLine(" <ss:Alignment ss:Horizontal=""Center""
ss:Vertical=""Center"" ss:WrapText=""1""/>")
fs.WriteLine(" <ss:Interior ss:Color=""#C0C0C0""
ss:Pattern=""Solid""/>")
fs.WriteLine(" </ss:Style>")
' Style for the column information
fs.WriteLine(" <ss:Style ss:ID=""2"">")
fs.WriteLine(" <ss:Alignment ss:Vertical=""Center""
ss:WrapText=""1""/>")
fs.WriteLine(" </ss:Style>")
fs.WriteLine(" </ss:Styles>")

' Write the worksheet contents
fs.WriteLine("<ss:Worksheet ss:Name=""Sheet1"">")
fs.WriteLine(" <ss:Table>")

For Each col As DataGridViewColumn In grdView.Columns
If col.Visible Then
fs.WriteLine(String.Format(" <ss:Column
ss:Width=""{0}""/>", col.Width))
End If
Next
fs.WriteLine(" <ss:Row>")

For Each col As DataGridViewColumn In grdView.Columns
If col.Visible Then
fs.WriteLine(String.Format(" <ss:Cell
ss:StyleID=""1""><ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>",
col.HeaderText))
End If
Next
fs.WriteLine(" </ss:Row>")

' Check for an empty row at the end due to Adding allowed on
the DataGridView
Dim subtractBy As Integer
If grdView.AllowUserToAddRows = True Then subtractBy = 2 Else
subtractBy = 1
' Write contents for each cell
For Each row As DataGridViewRow In grdView.Rows
fs.WriteLine(String.Format(" <ss:Row
ss:Height=""{0}"">", row.Height))
For Each col As DataGridViewColumn In grdView.Columns
If col.Visible Then
fs.WriteLine(String.Format(" <ss:Cell
ss:StyleID=""2""><ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>",
row.Cells(col.Name).Value.ToString))
End If
Next
fs.WriteLine(" </ss:Row>")
Next
' Close up the document
fs.WriteLine(" </ss:Table>")
fs.WriteLine("</ss:Worksheet>")
fs.WriteLine("</ss:Workbook>")
fs.Close()

' Open the file in Microsoft Excel
' 10 = SW_SHOWDEFAULT
ShellEx(Me.Handle, "Open", myFile, "", "", 10)
End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button4.Click
' Call the export sub
exportExcel(DataGridView1, "exportedData", ".xls",
My.Computer.FileSystem.SpecialDirectories.Desktop)
End Sub
================================================== ================================================== ==================================

AT THIS POINT IS WHERE I AM HAVING TROUBLES. I want either to import
the xlsx file to a SQL SERVER TABLE created on the fly with the fields
of that file OR create a table on the fly with whatever the user had
selected from the checkbox code above.

I had posted the export code at the begnning of the thread.

If anybody has a better idea on how I can achieve what I need to I'd
really be foever thankful!!! :-)

Thanks a lot guys!!!!!

Regards,

Tammy
Jun 27 '08 #6
Hi Tammy,

Did the code sample I posted earlier help you overcome the ISAM error
problem? Try that first and see if you can at least import data from
the Excel file. Once you can import data into your .Net app from Excel
then you can manipulate the data as you wish. But, as I mentioned
earlier, a caveat is that even if you successfully import the Excel data
into your app and display it in a datagridview control, if some of the
columns in the datagridview are not displaying any data where there is
data in the Excel sheet - that is where you have to prep the Excel sheet
(explicitly format the column in the Excel Sheet). Believe me, I have
been through this. Users at my place will receive Excel List from
government agencies and need to store the data in the sql server. I
told em that they have to prep the sheets before they can import the
data (and make sure to Copy the Excel file first and then SAVE the
changes to that copy of the Excel file - leaving the original file
alone).

Rich

*** Sent via Developersdex http://www.developersdex.com ***
Jun 27 '08 #7
"TG" wrote:
On May 28, 8:05�am, ma...@gemboxsoftware.com wrote:
Hi,

You could try to use some third party component for exporting data to
Excel file. I recommend you to use GemBox.Spreadsheet -- here is the
example of importing/exporting data from DataTable �to Excel files
(XLS, XLSX, CSV):http://www.gemboxsoftware.com/LDataTable.htm.

If you want to use free component, note that there is free version of
GemBox.Spreadsheet available -- you can even use it in your commercial
applications. Free version comes with 150 rows limit. You can find
free version here:http://www.gemboxsoftware.com/GBSpreadsheetFree.htm.

Mario
GemBox Software
--
GemBox.Spreadsheet for .NET - Easily read and write Excel (XLS, XLSX
or CSV)
or export to HTML files from your .NET apps. Seehttp://www.gemboxsoftware.com/GBSpreadsheet.htm
--

On May 28, 2:54 am, TG <jtam...@yahoo.comwrote:
On May 27, 4:58 pm, Rich P <rpng...@aol.comwrote:
Hi Tammy,
Here is a method which works for me for reading data from Excel and
writing it to Sql Server. �Note: �More times than not, you have to prep
the data in the Excel sheet - meaning - eliminating unused rows at then
end of the dataset in Excel, eliminating unused columns also at the end
of the dataset in Excel, making sure that the datatypes in each column
in the Excel sheet are valid (General format usually works OK but
sometimes have to format date fields as dates explicitly, text fields as
text, explicityly, numeric fields as numbers excplicitly). �The note
doesn't really have anything to do with "Missing ISAM", but just
something to be aware of.
-----------------------------------
Private Sub WriteDataToSqlServerFromExcel()
Dim da As OleDbDataAdapter, conn As OleDbConnection
conn = New OleDbConnection
conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data
source=C:\someDir\test1.xls;Extended Properties=Excel 8.0"
da = New OleDbDataAdapter
da.SelectCommand = New OleDbCommand
da.SelectCommand.Connection = conn
da.SelectCommand.CommandText = "Select * From [" Sheet1$]"
da.Fill(ds1, "Sheet1OLE")
Dim daS As New SqlDataAdapter, connS As New SqlConnection
connS.ConnectionString = "Data Source=MyServer;Initial
Catalog=MyDB;Integrated Security=True"
daS.SelectCommand = New SqlCommand
daS.SelectCommand.Connection = connS
daS.InsertCommand = New SqlCommand
daS.InsertCommand.Connection = connS
daS.SelectCommand.CommandText = "Select * From Sheet1DBTbl"
daS.Fill(ds1, "sht1DBtbl")
daS.InsertCommand.Parameters.Add("@fdl1", SqlDbType.VarChar, 50, "fld1")
daS.InsertCommand.Parameters.Add("@fdl2", SqlDbType.VarChar, 50, "fld2")
daS.InsertCommand.Parameters.Add("@fdl3", SqlDbType.VarChar, 50, "fld3")
..
daS.InsertCommand.CommandText = "Insert Into Sheet1DBTbl Select @fld1,
@fld2, @fld3, ..."
Dim reader As DataTableReader = ds1.Tables("Sheet1OLE").CreateDataReader
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
daS.Update(ds1, "sht1DBtbl")
End Sub
-------------------------------------------
There are 2 caveats here - 1) Sheet1DBTbl is an existing table on the
server DB (if there isn't one there - you need to create it either at
the server or from code). �2) However many fields there are in the Excel
sheet (and in the table on the sql server - which must match the same
number of columns there are in the Excel sheet and the Server DB table)
-- you have to add the same number of parameters to the DataAdapter
InsertCommand. �So the first half of the procedure above reads the data
from Excel into a memory table in the dataset (ds1) and the 2nd half of
the procedure writes the data from the OLE table to the Sql Server table
using a dataReader object.
One more note:
ds1.Tables("sht1DBtbl").Load(reader, LoadOption.Upsert)
(Except for the tableName -- use your own table name) this is the
correct syntax -- VB2005.
Rich
*** Sent via Developersdexhttp://www.developersdex.com***
Hi Rich!!
Thank you so much for yur reply!!!
I understand what you are doing but in my case I have an extra
problem. Sometimes the Excel file will have a minimum of 4 columns
(this ones will always be present) and then 5 other columns that might
all show up or not dependinf if the user select the checkbox. How do I
reflect that?
I cannot create a table manually in sql server, because i don't know
how many the user wants to see.
how can i do this with vb code?
thanks a lot for all ur time!!!!
regards,
Tammy- Hide quoted text -
- Show quoted text -

Thank you all for taking time to answer me.

Mario,

I do not need to export data to Excel.That part of my code works
perfect as it is.

Urkec and Rich,
My problem is importing back into a SQL SERVER TABLE that needs to be
created based on the EXCEL COLUMNS The Excel columns can vary from
only 4 to 9 and everything in between depending on what the user
selects in the code below.
HERE IS WHERE THE USER SELECTS WHICH FIELDS WILL BE SHOWN IN THE
DATAGRIDVIEW: (THIS WORKS PERFECT)

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click

Cursor.Current = System.Windows.Forms.Cursors.WaitCursor

Dim cn As New SqlConnection("Data Source=" &
lstServers.SelectedValue & ";Initial Catalog=" &
lstDatabases.SelectedValue & ";Integrated Security=SSPI")
Dim cmd As New SqlCommand("usp_DR_Spam_BB_Search_get_recs",
cn)
cmd.CommandTimeout = 0
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Matter",
lstDatabases.SelectedItem)
cmd.Parameters.AddWithValue("@FileSet",
lstFileSets.SelectedItem)

cn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ds As New DataSet()
Dim dt As New DataTable("Table1")
ds.Tables.Add(dt)
ds.Load(reader, LoadOption.PreserveChanges, ds.Tables(0))
DataGridView1.Font = New Font("SansSerif", 8.25,
FontStyle.Regular)
DataGridView1.DataSource = ds.Tables(0)

If DataGridView1.Rows.Count 0 Then

If CheckBox1.CheckState = True Then

DataGridView1.Columns("Last Name").Visible = True
ElseIf CheckBox1.CheckState = False Then

DataGridView1.Columns("Last Name").Visible = False

End If

If CheckBox2.CheckState = True Then

DataGridView1.Columns("First Name").Visible = True

ElseIf CheckBox2.CheckState = False Then

DataGridView1.Columns("First Name").Visible = False

End If

If CheckBox3.CheckState = True Then

DataGridView1.Columns("Domain").Visible = True

ElseIf CheckBox3.CheckState = False Then

DataGridView1.Columns("Domain").Visible = False

End If

If CheckBox4.CheckState = True Then

DataGridView1.Columns("Email").Visible = True

ElseIf CheckBox4.CheckState = False Then

DataGridView1.Columns("Email").Visible = False

End If

If CheckBox5.CheckState = True Then

DataGridView1.Columns("Subject").Visible = True

ElseIf CheckBox5.CheckState = False Then

DataGridView1.Columns("Subject").Visible = False

End If

Else

MessageBox.Show("There are no records using the fileset
selected, please try with a different fileset")

End If
Dim rowNumber As Integer = 1
For Each row As DataGridViewRow In DataGridView1.Rows
If row.IsNewRow Then Continue For
row.HeaderCell.Value = rowNumber.ToString
rowNumber = rowNumber + 1
Next
DataGridView1.AutoResizeRowHeadersWidth(DataGridVi ewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)

Cursor.Current = System.Windows.Forms.Cursors.Default

'cmd.Connection.Close()

End Sub

================================================== ================================================== =================================

HERE IS WHERE THE USER CAN EXPORT TO XLSX (THIS WORKS PERFECT)
Private Sub exportExcel(ByVal grdView As DataGridView, ByVal fileName
As String, _
ByVal fileExtension As String, ByVal filePath As String)

' Choose the path, name, and extension for the Excel file
Dim myFile As String = filePath & "\" & fileName &
fileExtension
' Open the file and write the headers
Dim fs As New IO.StreamWriter(myFile, False)
fs.WriteLine("<?xml version=""1.0""?>")
fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")
fs.WriteLine("<ss:Workbook xmlns:ss=""urn:schemas-microsoft-
com:office:spreadsheet"">")

' Create the styles for the worksheet
fs.WriteLine(" <ss:Styles>")
' Style for the column headers
fs.WriteLine(" <ss:Style ss:ID=""1"">")
fs.WriteLine(" <ss:Font ss:Bold=""1""/>")
fs.WriteLine(" <ss:Alignment ss:Horizontal=""Center""
ss:Vertical=""Center"" ss:WrapText=""1""/>")
fs.WriteLine(" <ss:Interior ss:Color=""#C0C0C0""
ss:Pattern=""Solid""/>")
fs.WriteLine(" </ss:Style>")
' Style for the column information
fs.WriteLine(" <ss:Style ss:ID=""2"">")
fs.WriteLine(" <ss:Alignment ss:Vertical=""Center""
ss:WrapText=""1""/>")
fs.WriteLine(" </ss:Style>")
fs.WriteLine(" </ss:Styles>")

' Write the worksheet contents
fs.WriteLine("<ss:Worksheet ss:Name=""Sheet1"">")
fs.WriteLine(" <ss:Table>")

This worked for me. I used "Excel 12.0 Xml" (surrounded by quotes) in the
connection string and needed to repeat the workbook path in the FROM clause
([c:\WorkbookName.xlsx].[Sheet1$])
Dim excelConnection As System.Data.OleDb.OleDbConnection = New
System.Data.OleDb.OleDbConnection("Provider=Micros oft.ACE.OLEDB.12.0;Data
Source=c:\WorkbookName.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES"";")
excelConnection.Open()
Dim excelCommand As New System.Data.OleDb.OleDbCommand("SELECT *
INTO [ODBC; Driver={SQL
Server};Server=ServerName;Database=DBName;Trusted_ Connection=yes].[TableName]
FROM [c:\WorkbookName.xlsx].[Sheet1$];", excelConnection)
excelCommand.ExecuteNonQuery()
--
urkec
Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: nicholas | last post by:
What would be the best and easiest way to implement a web page that allows me to: - import an Ms Excel-sheet in a database on a Ms Sql 2000 Server - this should be done through an asp.net...
1
by: gotgame0314 | last post by:
I am new to asp.net and would like to know the easiest way to view an Excel file in my asp app.
3
by: Santa-D | last post by:
I've got an excel sheet that I need to import into a table, however, I want the function to automatically manipulate the data prior to it being imported. For example, i have a field called and...
1
by: tamatem | last post by:
I have an excel sheet that contain colummns as in a table in a sql data base i want to transfer this data from the sheet to the table from business logic code layer not from the enterprise manager...
6
by: vj83 | last post by:
Hi, I have a C#.net application in which i have read the datas from excel sheet and displayed in a datagrid in my Aspx form. The code is here private void Button2_Click(object sender,...
1
ammoos
by: ammoos | last post by:
Hi friends Actually my problem is with the excel sheets. I have convert one of my access report to excel sheet that have too many records. After I convert the report to excel successfully, I cant...
3
by: inepu | last post by:
I have some excel sheets that I would like to manage in access. I've created the access tables and relationships; the excel sheet is only one table and with duplicate data, I'd like to make sure that...
0
by: satenova | last post by:
Hello Friends, I am newbie when it comes to vb.net and i need to import excel sheet into access db using vb.net application. Here is the code i use for now to upload excel sheet and it works...
2
by: vikassawant | last post by:
hi, It's very crazy problem.I want to import excel sheet data in to JTable but I can't find any solution. Actually what I want,suppose there are 7 rows and 5 columns in a table.If I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.