나는이 코드를 몇 시간 전에 작성한 응용 프로그램 II에서 함께 결합했습니다. .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