我想知道如何将 excel 文件导入 SQL Server 2008。例如,我有一个文本框、浏览按钮和导入按钮。我将单击浏览并浏览 excel 文件,然后单击导入以插入到数据库中的特定表中 excel 文件中的所有数据(不是创建新表)。有没有人知道这个代码?放在哪里?非常感谢您。:)
问问题
4699 次
2 回答
2
我还没有尝试过这个,但我认为它将有两个主要步骤。
- 您必须创建一个可以打开和读取 Excel 文件内容的函数
参考:如何在 C# 中打开 Excel 文件? - 读取excel文件内容并导入数据库表
参考: http: //www.codeproject.com/Articles/14528/Generate-SQL-INSERT-commands-programmatically
创建新表:
以编程方式创建sql表
希望能给点思路。
于 2013-05-31T02:51:55.857 回答
0
你可以试试这个
//代码 ....
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Web.Configuration
'Declare Variables - Edit these based on your particular situation
Dim sSQLTable As String = "TempTableForExcelImport"
Dim sExcelFileName As String = "myExcelFile.xls"
Dim sWorkbook As String = "[WorkbookName$]"
'Create our connection strings
Dim sExcelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(sExcelFileName) & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Dim sSqlConnectionString As String = WebConfigurationManager.ConnectionStrings("MyConnectionString").ToString
'Execute a query to erase any previous data from our destination table
Dim sClearSQL = "DELETE FROM " & sSQLTable
Dim SqlConn As SqlConnection = New SqlConnection(sSqlConnectionString)
Dim SqlCmd As SqlCommand = New SqlCommand(sClearSQL, SqlConn)
SqlConn.Open()
SqlCmd.ExecuteNonQuery()
SqlConn.Close()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(sExcelConnectionString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM " & sWorkbook), OleDbConn)
OleDbConn.Open()
Dim dr As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(sSqlConnectionString)
bulkCopy.DestinationTableName = sSQLTable
bulkCopy.WriteToServer(dr)
OleDbConn.Close()
于 2013-10-18T08:43:52.060 回答