之前做项目的时候,查阅了大量资料,终于解决了将归档数据导出到excel的功能,这里将我的代码发出来以供参考。注意,里面的一些参数需要根据你的具体需要进行修改。
本人还总结了一份技术文档,由于这里不能上传上传文档,请到我的个人博客里下载吧:
http://www.ucooper.com/wincc-summary.htmlSub OnLButtonDown(ByVal Item, ByVal Flags, ByVal x, ByVal y)
Dim sPro,sDsn,sSer,sCon,sSql,oRs,conn,oCom,oItem,m,n,s,i,hourdate,secdate
Dim k,oList,objExcelApp,oItem2,dt1,dt2,dstr1,dstr2,dstr3,dstr4
sPro = "Provider=WinCCOLEDBProvider.1;"
sDsn = "Catalog=CC_tanks_09_07_14_10_38_56R;" '根据实际情况修改,查SQLSERVER
sSer = "Data Source=.\WinCC"
sCon = sPro + sDsn + sSer
sSql = "TAG:R,'tanks\aa','2009-07-16 12:30:00.000','2009-07-16 13:00:00.000'" 'tanks是归档名 aa 是变量名
MsgBox "Open with:" & vbCr & sCon & vbCr & sSql & vbCr
Set conn = CreateObject("ADODB.Connection")
conn.ConnectionString = sCon
conn.CursorLocation = 3
conn.Open
Set oRs = CreateObject("ADODB.Recordset")
Set oCom = CreateObject("ADODB.Command")
oCom.CommandType = 1
Set oCom.ActiveConnection = conn
oCom.CommandText = sSql
Set oRs = oCom.Execute
n=oRs.RecordCount
MsgBox(n)
'oRs.MoveFirst
Set objexcelApp=CreateObject("excel.application")
objexcelApp.visible=True
objexcelapp.workbooks.open"d:\book.xls" '首先要创建这个文件
objExcelApp.Sheets(1).Range("a"&Trim(1)) =oRs.Fields(0).Name
objExcelApp.Sheets(1).Range("b"&Trim(1)) = oRs.Fields(1).Name
objExcelApp.Sheets(1).Range("c"&Trim(1)) = oRs.Fields(2).Name
objExcelApp.Sheets(1).Range("d"&Trim(1)) = oRs.Fields(3).Name
objExcelApp.Sheets(1).Range("e"&Trim(1)) = oRs.Fields(4).Name
For i=1 To oRs.RecordCount
'NewDate = DateAdd("h", 8, "FormatNumber(oRs.Fields(1).value, 1)")
objExcelApp.Sheets(1).Range("a"&Trim(i+1)) =oRs.Fields(0).value
objExcelApp.Sheets(1).Range("b"&Trim(i+1)) =DateAdd("h",+8,oRs.Fields(1).value)
objExcelApp.Sheets(1).Range("c"&Trim(i+1)) =oRs.Fields(2).value
objExcelApp.Sheets(1).Range("d"&Trim(i+1)) =oRs.Fields(3).value
objExcelApp.Sheets(1).Range("e"&Trim(i+1)) =oRs.Fields(4).value
oRs.MoveNext
Next
oRs.Close
Set oRs = Nothing
conn.Close
Set conn = Nothing
objexcelapp.activeworkbook.save
objexcelapp.workbooks.close
'Set objexcelapp.workbooks=Nothing
objexcelapp.quit
MsgBox("aa")
Set objexcelapp=Nothing
MsgBox("bb")
MsgBox("导出成功!!")
End Sub