Byte Array for Excel

I am trying to convert an array of bytes 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 this with this, which I found on the Internet:

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 message:

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 any difference in how binary writing and deserialization work? How can i fix this?

thank

+5
source share
1 answer

I assume that you are trying to do Object workBook = ByteArrayToObject(renderedBytes);that does not work properly.

, Response.BinaryWrite(renderedBytes); , ( , , , Excel), renderedBytes Excel Excel.

, Excel, renderedBytes, BinaryFormatter. BinaryFormatter, , , Excel: (?) . , BinaryFormatter.Serialize. Excel .

Excel #, , , EPPlus:

private ExcelPackage ByteArrayToObject(byte[] arrBytes)
{
    using (MemoryStream memStream = new MemoryStream(arrBytes))
    {
        ExcelPackage package = new ExcelPackage(memStream);
        return package;
    }
}
+8

Source: https://habr.com/ru/post/1541281/


All Articles