Byte array to excel workbook

让人想犯罪 __ 提交于 2020-08-27 06:27:51

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/23762274/byte-array-to-excel-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!