有時(shí),我們需要把一篇word文章保存到數(shù)據(jù)庫中以方便日后搜索使用,但如何做到這一點(diǎn)呢?下面就給出兩種把word文檔存儲(chǔ)到數(shù)據(jù)庫中的方法。
第一種方法:把整個(gè)word文檔保存到數(shù)據(jù)庫中,這樣不僅保存了word文檔中的內(nèi)容,也把word中的格式也保存起來了。
在保存時(shí),如果使用的數(shù)據(jù)庫為SQL Server,則保存word文檔的字段應(yīng)使用Binary數(shù)據(jù)類型,如果使用ACCESS數(shù)據(jù)庫,則應(yīng)使用OLE對(duì)象。
完整源代碼如下:
'將任何文件從數(shù)據(jù)庫中下載到本地:
Public Function LoadFile(ByVal col As ADODB.Field, ByVal FileName As String) As Boolean '獲得binary數(shù)據(jù)
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
'將文件從本地上傳到數(shù)據(jù)庫中
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
第二種方法:
在設(shè)計(jì)數(shù)據(jù)庫時(shí),設(shè)計(jì)字段有:wjmc(文件名),wjsx (文件的擴(kuò)展名),Wjnr(文件內(nèi)容為二進(jìn)制數(shù)據(jù)類型)。(若數(shù)據(jù)庫采用access數(shù)據(jù)庫則文件內(nèi)容“ole對(duì)象”,sql server數(shù)據(jù)庫為“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為文件的名稱加擴(kuò)展名
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
如果你需要這篇文章,則就把它收藏好吧。
新聞熱點(diǎn)
疑難解答