|
发表于 2020-10-16 17:00:01
|
显示全部楼层
以下是我从DataTable到Excel的程序段,看看有什么帮助
Public Sub DStoXls(ByVal Table As DataTable, ByVal DefFileName As String)
Dim MyOleDbCn As New System.Data.OleDb.OleDbConnection
Dim MyOleDbCmd As New System.Data.OleDb.OleDbCommand
Dim MyTable As New DataTable
Dim intRowsCnt, intColsCnt As Integer
Dim strSql As String, strFlName As String
Dim Fso As New System.Object
If Table Is Nothing Then
MessageBox.Show("未取得數據,無法導出", "導出錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
MyTable = Table
If MyTable.Rows.Count = 0 Then
MessageBox.Show("未取得數據,無法導出", "導出錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Dim FileName As String
Dim SaveFileDialog As New SaveFileDialog
SaveFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
SaveFileDialog.Title = "保存為"
SaveFileDialog.Filter = ".xls|*.xls"
SaveFileDialog.FileName = DefFileName
If (SaveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
FileName = SaveFileDialog.FileName
' TODO: 在此加入開啟檔案的程式碼。
End If
If FileName = "" Then Exit Sub
strFlName = FileName
If Dir(FileName) <> "" Then
Kill(FileName)
End If
Try
Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
MyOleDbCn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;" & _
"Data Source=" & strFlName & ";" & _
"Extended ProPerties=""Excel 8.0;HDR=Yes;"""
MyOleDbCn.Open()
MyOleDbCmd.Connection = MyOleDbCn
MyOleDbCmd.CommandType = CommandType.Text
'第一行插入列标题
strSql = "CREATE TABLE " & DefFileName & "("
For intColsCnt = 0 To MyTable.Columns.Count - 1
If intColsCnt <> MyTable.Columns.Count - 1 Then
strSql = strSql & ChangeChar(MyTable.Columns(intColsCnt).Caption) & " text,"
Else
strSql = strSql & ChangeChar(MyTable.Columns(intColsCnt).Caption) & " text)"
End If
Next
MyOleDbCmd.CommandText = Replace(strSql, ".", "_") '創建表的時候,不允許有“.”的字段名,所以要用“ˍ”來替換
MyOleDbCmd.ExecuteNonQuery()
'插入各行
For intRowsCnt = 0 To MyTable.Rows.Count - 1
strSql = "INSERT INTO " & DefFileName & " VALUES('"
For intColsCnt = 0 To MyTable.Columns.Count - 1
If intColsCnt <> MyTable.Columns.Count - 1 Then
strSql = strSql & ChangeChar(MyTable.Rows(intRowsCnt).Item(intColsCnt)) & "','"
Else
strSql = strSql & ChangeChar(MyTable.Rows(intRowsCnt).Item(intColsCnt)) & "')"
End If
Next
MyOleDbCmd.CommandText = strSql
MyOleDbCmd.ExecuteNonQuery()
Next
MessageBox.Show("数据已经成功导入EXCEL文件" & strFlName, "数据导出", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ErrCode As Exception
MsgBox("错误信息:" & ErrCode.Message & vbCrLf & vbCrLf & _
"引发事件:" & ErrCode.TargetSite.ToString, MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "错误来源:" & ErrCode.Source)
Exit Sub
'Finally
MyOleDbCmd.Dispose()
MyOleDbCn.Close()
MyOleDbCn.Dispose()
End Try
End Sub |
|