1

我正在尝试通过 DbAdapter 将 SpreadsheetGear Excel 工作簿保存到 BLOB 字段

Try
    Dim stream As New System.IO.MemoryStream()
    customFormatWorkBook.SaveToStream(stream, SpreadsheetGear.FileFormat.Excel8)
    Dim bytes(stream.Length - 1) As Byte
    stream.Read(bytes, 0, stream.Length)
    docDataSet.Tables(0).Rows(0)("FORMATTED_DOC") = bytes
    stream.Close()
Catch ex As Exception
End Try
docDataAdapter.Update(docDataSet, "DOCUMENTS")

此代码保存了一个完全混乱的 Excel 文件。
如果我从数据库中导出它,它甚至会导致 MS Excel 崩溃(嗯……很好的异常处理微软!)

就在Dim bytes(stream.Length - 1) As Byte完全可读之前(我尝试用SpreadsheetGear的方法stream重新打开它)OpenFromStream

另外,我验证了保存到文件,然后将其加载到 a 中FileStream,转换为 aByte()并保存到 BLOB 也可以正常工作,但我只是不想访问文件系统:

customFormatWorkBook.SaveAs("C:\Users\teejay\Desktop\prova.xls", SpreadsheetGear.FileFormat.Excel8)

Try    
    Dim stream As FileStream = New FileStream("C:\Users\teejay\Desktop\prova.xls", FileMode.Open)
    Dim bytes(stream.Length - 1) As Byte
    stream.Read(bytes, 0, stream.Length)
    docDSet.Tables(0).Rows(0)("FORMATTED_DOC") = bytes
    stream.Close()
Catch ex As Exception
End Try
docDataAdapter.Update(docDataSet, "DOCUMENTS")

你能帮助我吗?

4

1 回答 1

2

我怀疑问题是SaveToStream让您留在end流中;不幸的是,stream.Read(bytes, 0, stream.Length)仍然可以工作;它只会将 0 个字节读入您的数组。您可以通过检查 from 的返回值来验证这一点stream.Read,即读取的字节总数。

因此,如果您stream.Position在尝试读取之前将其设置为 0:

Try
    Dim stream As New System.IO.MemoryStream()
    customFormatWorkBook.SaveToStream(stream, SpreadsheetGear.FileFormat.Excel8)
    stream.Position = 0;
    Dim bytes(stream.Length - 1) As Byte
    stream.Read(bytes, 0, stream.Length)
    docDataSet.Tables(0).Rows(0)("FORMATTED_DOC") = bytes
    stream.Close()
Catch ex As Exception
End Try
docDataAdapter.Update(docDataSet, "DOCUMENTS")

那么这应该工作。

于 2013-06-25T10:28:24.833 回答