【问题标题】:Convert Access Attachment data type to file system files将 Access Attachment 数据类型转换为文件系统文件
【发布时间】:2015-05-18 13:35:31
【问题描述】:

我有很多文件作为附件存储在 Access 数据库中。我要将数据移动到 SQL 服务器,为此我需要提取附加文件并将它们转换为文件系统文件。

此 sn-p 适用于图像和 pdf 文件,但不适用于 Word 或 Excel 等 Office 文档。我认为它与编码有关,但我没有任何线索。有什么想法吗?

Dim dbs As Database
Dim rs As Recordset
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("table1")
With rs
Do While Not .EOF
    Set rsRec = rs.Fields("AttFiles").Value
    While Not rsRec.EOF
        NameOfFile = "C:\temp\" & rsFil.Fields("FileName")
        Open NameOfFile For Binary Access Write As #1
        Put #1, , rsRec.Fields("FileData").Value
        Close #1
        rsRec.MoveNext
    Wend
    .MoveNext
Loop
End With
rs.Close
dbs.Close

【问题讨论】:

    标签: sql-server ms-access character-encoding vba


    【解决方案1】:

    如果文件实际上是附件类型,那么您不妨使用 Microsoft Access 对象库的 Recordset2。类似的,

    Public Sub exportDocument(tableName As String, fieldName As String, uniqueID As Long)
    On Error GoTo Err_SaveImage
        Dim rsParent As DAO.Recordset2
        Dim rsChild As DAO.Recordset2
        Dim saveAsName As String
    
        Set rsParent = CurrentDb.OpenRecordset("SELECT " & tableName & ".* " & _
                                               "FROM " & tableName & " WHERE " & tableName & "." & fieldName & " = " & uniqueID)
        Set rsChild = rsParent.Fields("fileData").Value
    
        If rsChild.RecordCount <> 0 Then
            If Dir(Environ("userprofile") & "\My Documents\tmp\", vbDirectory) <> "." Then MkDir Environ("userprofile") & "\My Documents\tmp\"
    
            saveAsName = Environ("userprofile") & "\My Documents\tmp\" & rsChild.Fields("FileName")
    
            rsChild.Fields("fileData").SaveToFile saveAsName
    
            FollowHyperlink saveAsName
        End If
    Exit_SaveImage:
        Set rsChild = Nothing
        Set rsParent = Nothing
        Exit Sub
    
    Err_SaveImage:
        If Err = 3839 Then
            Resume Next
        Else
            MsgBox "Some Other Error occured!" & vbCrLf & vbCrLf & Err.Number & " - " & Err.Description, vbCritical
            Resume Exit_SaveImage
        End If
    End Sub
    

    以上代码会将文件保存到saveAsName 中指定的位置。我在 WHERE 条件中有特定的唯一 ID。如果要导出所有文档,可以相应地更改代码,但可能必须遍历记录集。我希望这会有所帮助!

    【讨论】:

    • 谢谢,你是对的。 SaveToFile 在附加文件的开头剪掉了废话。 pdf 阅读器忽略但 Office 不会忽略的废话。另见:stackoverflow.com/questions/25864092
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2020-06-22
    相关资源
    最近更新 更多