已经从UI中将.xlsx文件保存到数据库中。现在我正在使用下面的代码从数据库中读取数据并将其写入临时位置文件。
Dim Buffer() As Byte
Dim Amount As Integer = 2000
Dim TripCount As Integer = 0
Dim reminder As Integer = 0
ReDim Buffer(FileSize)
TripCount = FileSize \ Amount
reminder = FileSize Mod Amount
If reminder > 0 Then
TripCount = TripCount + 1
End If
For cnt As Integer = 0 To TripCount - 1
Dim Offset As Integer = 1
Offset = Offset + cnt * Amount
Dim ReadCount As Integer = Amount
If cnt = TripCount - 1 Then
ReadCount = CInt(FileSize) - (cnt * Amount)
End If
Dim b() As Byte = GetFileData(CLng(documentId), ReadCount, Offset) 'GetFileData methdo as last code segment
Array.Copy(b, 0, Buffer, Offset - 1, b.Length)
Next
Dim downloadFile As New FileInfo(selectedPath + "\" + FileName)
Using bw As New BinaryWriter(downloadFile.OpenWrite)
bw.Write(Buffer)
bw.Close()
End Using
Public Function GetFileData(ByVal documentId As Long, ByVal amount As Integer, ByVal offset As Integer) As Byte()
Dim RetVal() As Byte = Nothing
Dim b1 As Byte() = Nothing
Try
Dim sql As String = ""
ReDim RetVal(amount)
sql = " SELECT DBMS_LOB.SUBSTR(F.DF_FILE," + amount.ToString + "," + offset.ToString + " ) DATA"
sql += " FROM table_name F"
sql += " WHERE F.docid = " + documentId.ToString
Dim data As DataTable = FetchData(sql)
b1 = CType(data.Rows(0)("DATA"), Byte())
Array.Copy(b1, 0, RetVal, 0, b1.Length)
Catch ex As Exception
End Try
Return RetVal
End Function
将文件放入临时位置后,我试图打开它,但它会丢失以下错误。
Excel在' filename.xlsx'中找到了不可读的内容。你想恢复这个工作簿的内容吗?如果您信任此工作簿的来源,请单击是
但是同一组代码适用于.xls格式文件。
答案 0 :(得分:0)
问题在于数组大小。
如果文件大小为2000字节。那么
Redim Buffer(FileSize)
此缓冲区的Redim数组大小将为2000 + 1 = 2001
然后从数据库获取并放入Buffer数组并将其写入文件,如下所示。
Dim downloadFile As New FileInfo(selectedPath + "\" + FileName)
Using bw As New BinaryWriter(downloadFile.OpenWrite)
bw.Write(Buffer)
bw.Close()
End Using
文件大小增加1个字节。在这种情况下,文件大小为2001字节。所以它显示错误。
现在我已经用下面的内容替换了上面的内容,并且它完美无缺。
Using bw As New BinaryWriter(downloadFile.OpenWrite)
Dim newBuffer(((Buffer.Length) - 2)) As Byte
Array.Copy(Buffer, 0, newBuffer, 0, ((Buffer.Length) - 2))
bw.Write(newBuffer)
bw.Close()
End Using
在上面的代码中我已经声明了另一个新数组newBuffer并将数据从旧数组Buffer复制到新数组newBuffer,从0索引到(旧数组的长度 - 2)以容纳文件大小。