标题:如何把一篇Word文章保存到数据库中
作者:网友
日期:2023-06-12 12:11:34
内容:

有时,我们需要把一篇word文章保存到数据库中以方便日后搜索使用,但如何做到这一点呢?下面就给出两种把word文档存储到数据库中的方法。

第一种方法:把整个word文档保存到数据库中,这样不仅保存了word文档中的内容,也把word中的格式也保存起来了。

在保存时,如果使用的数据库为SQL Server,则保存word文档的字段应使用Binary数据类型,如果使用ACCESS数据库,则应使用OLE对象。

完整源代码如下:    
    '将任何文件从数据库中下载到本地:
    Public Function LoadFile(ByVal col As ADODB.Field, ByVal FileName As String) As Boolean '获得binary数据
    On Error GoTo myerr:
     Dim arrBytes() As Byte
     Dim FreeFileNumber As Integer
     lngsize = col.ActualSize
     arrBytes = col.GetChunk(lngsize)
     FreeFileNumber = FreeFile
     Open FileName For Binary Access Write As #FreeFileNumber
     Put #FreeFileNumber, , arrBytes
     Close #FreeFileNumber
     LoadFile = True
    myerr:
     If Err.Number <> 0 Then
     LoadFile = False
     Err.Clear
     End If
    End Function
    
    '将文件从本地上传到数据库中
    Public Function UpLoadFile(ByVal FileName, ByVal col As ADODB.Field) As Boolean
     On Error GoTo myerr:
     Dim arrBytes() As Byte
     Dim FreeFileNumber As Integer
     FreeFileNumber = FreeFile
     Open FileName For Binary As #FreeFileNumber
     n = LOF(FreeFileNumber)
     ReDim arrBytes(1 To n) As Byte
     Get #FreeFileNumber, , arrBytes
     Close #FreeFileNumber
     col.AppendChunk (arrBytes)
     UpLoadFile = True
    myerr:
     If Err.Number <> 0 Then
     UpLoadFile = False
     Err.Clear
     End If
    End Function

第二种方法:

在设计数据库时,设计字段有:wjmc(文件名),wjsx (文件的扩展名),Wjnr(文件内容为二进制数据类型)。(若数据库采用access数据库则文件内容“ole对象”,sql server数据库为“image”) 

该程序可以操作所有的文件类型。
    Dim Wenjian As String
    
    Dim RD As Byte
    
    Dim SIZE As Long
    
    Const MYSIZE = 1048576
    
    Dim WENJIANN() As Byte
    
     Dim Rs As New ADODB.Recordset
    
     Rs.Open "select * from wj", Cn, 1, 3
    
     Rs.AddNew
    
     Rs!wjmc = Mid(Name, 1, InStr(Name, ".") - 1)
    
     Rs!wjsx = Mid(Name, InStr(Name, ".") + 1)
    
     ‘name为文件的名称加扩展名
    
     Open Filename For Binary Access Read As #1
    
     SIZE = LOF(1)
    
     Do While SIZE - MYSIZE >= 0
    
     ReDim WENJIANN(MYSIZE) As Byte
    
     Get #1, , WENJIANN
    
     Rs!wjnr.AppendChunk WENJIANN
    
     SIZE = SIZE - MYSIZE
    
     Loop
    
     If SIZE > 0 Then
    
     ReDim WENJIANN(SIZE) As Byte
    
     Get #1, , WENJIANN
    
     Rs!wjnr.AppendChunk WENJIANN
    
     End If
    
     Close #1
    
     Rs.Update
    
     Set Rs = Nothing

如果你需要这篇文章,则就把它收藏好吧。


返回列表 网站首页