Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte array to excel workbook

I am trying to convert a byte array to an excel workbook. When I do this with

Response.BinaryWrite(renderedBytes);

it works fine and the file is as expected. But when I try to do it with this which I found online:

private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object)binForm.Deserialize(memStream);
    return obj;
}

I get an error:

System.Runtime.Serialization.SerializationException: Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.

Is there a difference in how binary write and deserialize work? How can I fix it?

Thanks

like image 933
user3657017 Avatar asked May 20 '14 14:05

user3657017


1 Answers

I am assuming you are trying to do Object workBook = ByteArrayToObject(renderedBytes); which turns out not to work as expected.

Since you are stating that Response.BinaryWrite(renderedBytes); works as expected (by which you probably mean you can save the response and open it in Excel), the binary data in renderedBytes is a valid Excel workbook in the Excel file format.

It appears that you are trying to parse the data in the Excel file format contained in renderedBytes using a BinaryFormatter. BinaryFormatter however, does not know how to parse the Excel file format: it is designed to parse a specific (proprietary?) binary serialization format and nothing else. That is, you can only use it to deserialize data that was generated with a call to BinaryFormatter.Serialize. An Excel file does not meet this requirement.

In order to actually parse an Excel workbook in binary form to a C# object, you will have to use a library that can do so, such as EPPlus:

private ExcelPackage ByteArrayToObject(byte[] arrBytes)
{
    using (MemoryStream memStream = new MemoryStream(arrBytes))
    {
        ExcelPackage package = new ExcelPackage(memStream);
        return package;
    }
}
like image 132
TC. Avatar answered Sep 20 '22 23:09

TC.