简体   繁体   中英

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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM