【问题标题】:SaveToStream then write to BLOB mess up the Excel fileSaveToStream 然后写入 BLOB 搞乱 Excel 文件
【发布时间】:2013-06-25 09:59:50
【问题描述】:

我正在尝试通过 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 崩溃 (mmh.. 很好的异常处理 Microsoft!)

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

此外,我验证了保存到文件,然后将其加载到 FileStream,转换为 Byte() 并保存到 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")

你能帮帮我吗?

【问题讨论】:

  • 在阅读流之前,请尝试设置stream.Position = 0;,这样您就可以再次“回到流的开头”。 SaveToStream 函数可能无法正确重新定位流。 stream.Read 中的第二个参数是您当前的偏移量,而不是 position=0
  • @dash 谢谢!!!!!! FileStream 重新定位流,但 SSG 的 SaveToStream 没有(位置是 512,看起来很随机!)。请写下您的评论作为答案,以便我接受!

标签: vb.net blob memorystream spreadsheetgear


【解决方案1】:

我怀疑问题是SaveToStream 将您留在流的end;不幸的是,stream.Read(bytes, 0, stream.Length) 仍然有效;它只会将 0 个字节读入您的数组。您可以通过检查来自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")

那应该可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2017-09-08
    • 2014-09-09
    • 2013-12-18
    • 1970-01-01
    • 2011-12-06
    • 2013-10-14
    相关资源
    最近更新 更多