0
根據我的要求,我想讀取和導出數據從Excel(駐留在網絡驅動器)到sqlserver 2012. 我將創建控制檯應用程序(exe)使用c#(.net框架4.5)..這個控制檯 應用程序將計劃在Web服務器上每天使用窗口調度程序運行。從excel文件導出數據到Sqlserver 2012
你能告訴我什麼是最好的方法來做到這一點...保持性能也牢記在心。 如果任何人有現成的代碼/組件,然後請分享。
根據我的要求,我想讀取和導出數據從Excel(駐留在網絡驅動器)到sqlserver 2012. 我將創建控制檯應用程序(exe)使用c#(.net框架4.5)..這個控制檯 應用程序將計劃在Web服務器上每天使用窗口調度程序運行。從excel文件導出數據到Sqlserver 2012
你能告訴我什麼是最好的方法來做到這一點...保持性能也牢記在心。 如果任何人有現成的代碼/組件,然後請分享。
我把這段代碼從一段時間前寫過的應用程序拼湊在一起。它使用.NET OLEDB從Excel文件導入數據,在這種情況下導入MS-Access數據庫,但SQL-Server的概念相同。你需要將它適應表格,Excel文件和數據使用的是:
換人要求:
YourConnectionString
YourSLQTable
Your SQL Columns: col1, col2, coln
Your Column Valuess: @cdata1, cdata2, cdatan
UniqueValue: the columns(s) that make your SQL table unique
Note that parameter values must be supplied in the order they are used in the SQL statement, not in the named list, ex. New String() {"UV", "cdata1", "cdata2"}, _
Public Shared connString As String = _
Configuration.ConfigurationManager.ConnectionStrings("xls").ConnectionString
Public Shared connStringX As String = _
Configuration.ConfigurationManager.ConnectionStrings("xlsx").ConnectionString
Public Shared Sub ImportExcelFile(ByRef Filepath As String)
Dim ConnectionString = IIf(Filepath.EndsWith("xlsx"), connStringX, connString)
Try
Using axsCon = New OleDbConnection("YourConectionString")
axsCon.Open()
Using m_connexcel As OleDbConnection = _
New OleDbConnection(String.Format(ConnectionString, Filepath))
m_connexcel.Open()
Dim Sheetname As String = GetFirstExcelWorksheetName(m_connexcel, Filepath)
Using cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [" & Sheetname & "]", m_connexcel)
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
If Common.GetScalar(axsCon, "SELECT Count(*) FROM YourSQLTable WHERE [UniqueValue][email protected] ", _
New String() {"UV"}, New Object() {oRDR.GetValue(0)}) = 0 Then
Common.ExecuteSQL(axsCon, _
"INSERT INTO YouSQLTable(col1, col2, coln) " & _
"VALUES(@C1,@C2,@CN)", New String() {"Cdata1", "Cdata2", "CdataN"}, _
New Object() {oRDR.GetValue(0), oRDR.GetValue(1), oRDR.GetValue(2)})
Else
Common.ExecuteSQL(axsCon, _
"UPDATE YourSQLTable SET [email protected],[email protected],[email protected] " & _
"WHERE [email protected]", New String() {"UV", "cdata1", "cdata2"}, _
New Object() {oRDR.GetValue(1), oRDR.GetValue(2), oRDR.GetValue(0)})
End If
End While
End Using
End Using
m_connexcel.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
'需要此功能,找到第一個工作表中,可能並不適用於您的應用。
Private Shared Function GetFirstExcelWorksheetName(ByVal m_connexcel As OleDbConnection, ByVal Filepath As String) As String
Try
Dim ExcelSheets As DataTable = m_connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
Return ExcelSheets.Rows(0).Item("TABLE_NAME")
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function