Question

I'm trying to save a SpreadsheetGear Excel workbook to a BLOB field thru a DbAdapter

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")

This code saves a completely messed up Excel file.
If I export it from the DB it even crashes MS Excel (mmh.. good exception handling Microsoft!)

Just before Dim bytes(stream.Length - 1) As Byte the stream is perfectly readable (I tried re-opening it with SpreadsheetGear's OpenFromStream method)

Also, I verified that saving to a file, then loading it in a FileStream, transforming to a Byte() and saving to BLOB also works fine, but I just don't want to access the file system:

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")

Can you help me?

Was it helpful?

Solution

I suspect the issue is that SaveToStream is leaving you at the end of the stream; unfortunately, stream.Read(bytes, 0, stream.Length) will still work; it will just read 0 bytes into your array. You can verify this by checking the return value from stream.Read, which is the total number of bytes read.

So, if you set the stream.Position to 0 before attempting to read it:

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")

Then that should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top