2011-07-25 16:43:23| 分类: |字号
把excel中的数据导入SQL SERVER数据库(access数据类似):
Private Sub Command1_Click()
Dim strconn As String ' 定义Excel 连接字符串Dim cn As ADODB.Connection ' 定义Excel 连接Set cn = New ADODB.Connection' 初始化commandialog1 的属性,选取Excel 文件,文' 件名保存在CommanDialog1.filename 中备用CommonDialog1.Filter = " 电子表格文件(.xls) |*.xls"CommonDialog1.DialogTitle = " 请选择要导入的文件"CommonDialog1.ShowOpen' 设置连接SQL 数据库的连接字符串strtemp = " [odbc;Driver= {SQL Server} ;Server=(local);Database=Afws;UID=sa;PWD=sa]"' 设置Excel 数据连接strconn = " Provider =Microsoft.Jet.OLEDB.4.0;Data Source=" & CommonDialog1.FileName & " ; Extended Properties=Excel 8.0" cn.Open strconnstrSql = "insert into " & strtemp & ".hw_level1 select * from [sheet1$]"cn.Execute strSql, lngRecsAff, adExecuteNoRecordsMsgBox " 成功导入到SQL 数据库中!", vbExclamation + vbOKOnlycn.CloseSet cn = NothingEnd Sub从access数据库中导出数据到为excel(sql数据库类似):
dim conn as adodb.connection
Dim rs1 As New ADODB.Recordsetdim sql as stringset conn=new adodb.connectionif conn.state<>0 then conn.closeconn.open "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & App.Path &"\sclsylb.mdb"sql="SELECT * FROM QS800" 'QS800表你应该很熟悉if rs1.state<>0 then rs1.closers1.cursorlocation=aduserclientrs1.open sql,conn,1,3'导出xls表Dim xlApp As New Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorksheetDim xlQuery As Excel.QueryTable'On Error GoTo OutPutErrSet xlBook = xlApp.Workbooks().AddSet xlSheet = xlBook.Worksheets("sheet1")Set xlQuery = xlSheet.QueryTables.Add(rs1, xlSheet.Range("a1 "))With xlQuery .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = True .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = TrueEnd WithxlQuery.FieldNames = TruexlQuery.Refreshcmdlg.Flags = 2cmdlg.Filter = "EXCEL文档(*.xls)"cmdlg.ShowSaveIf cmdlg.FileName <> "" Then xlApp.DisplayAlerts = False xlBook.SaveAs FileName:=cmdlg.FileName If MsgBox("导出成功,是否打开查看?", vbOKCancel, "导出EXCEL") = vbOK Then xlApp.Workbooks().Open cmdlg.FileName xlApp.Visible = True Else xlApp.Quit End IfEnd IfIf xlApp <> Null Then Set xlApp = Nothingset conn=nothingset rs1=nothing