如何使用vba从excel从数据库(varbinary max)检索pdf文件

时间:2016-05-12 12:37:13

标签: excel-vba vba excel

我不知道如何通过excel vba从数据库中检索或提取pdf文件? (c#,asp中提供了很多帮助......)

文件存储在SQL Server数据库中的varbinary max type字段中。

我可以通过VBA连接或访问记录集,之后如何从该记录集中提取它

1 个答案:

答案 0 :(得分:0)

Dim cn  As ADODB.Connection
Dim rs  As ADODB.Recordset
Dim sql As String
Dim oStream As ADODB.Stream

Set cn = New ADODB.Connection

'Here I use default admin user 'sa' and password is blank
cn.Open "Provider = sqloledb;" & _
        "Data Source=ServerNameOrIP;" & _
        "Initial Catalog=DBName;" & _
        "User ID=sa;" & _
        "Password=;"""

'your sql statment including varbinary max field here it is FILEDATA
sql = " select EMAILID,EMAILFROM,EMAILTO,EMAILSUBJECT,FILEDATA from Tbl "


Set rs = New ADODB.Recordset

rs.Open sql, cn

Do Until rs.EOF
    Set oStream = New ADODB.Stream
    With oStream
         .Type = adTypeBinary
         .Open
         .Write rs.Fields(4).Value
         'Here I use 1st field value as file name i.e. rs.fiedls(0).value 
         'In addition you can join drive and/or folder path to save another location
         .SaveToFile rs.Fields(0).Value & ".pdf", adSaveCreateOverWrite
         .Close
    End With
    Set oStream = Nothing
    rs.MoveNext
Loop


rs.Close
cn.Close