Byte数组到Excel工作簿
我想一个字节数组转换为Excel工作簿。当我做这与
I am trying to convert a byte array to an excel workbook. When I do this with
Response.BinaryWrite(renderedBytes);
它工作正常,该文件是为expeced。但是,当我尝试这里面我在网上找到做到这一点:
it works fine and the file is as expeced. 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?
感谢
我假设你正在尝试做的对象的工作簿= ByteArrayToObject(renderedBytes);
果然不按预期运行。
I am assuming you are trying to do Object workBook = ByteArrayToObject(renderedBytes);
which turns out not to work as expected.
既然你声称 Response.BinaryWrite(renderedBytes);
预期(由你大概的意思是,你可以保存响应,并在Excel中打开它)的作品中,在 renderedBytes
二进制数据是在Excel文件格式的有效Excel工作簿。
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.
看样子,你正在试图使用包含在 renderedBytes
Excel文件格式解析数据的的BinaryFormatter
。 的BinaryFormatter
但是,不知道如何分析Excel文件格式:它是专门用来解析一个特定的(专有的?)二进制序列化格式的闲来无事。也就是说,你只能用它来反序列化与调用 BinaryFormatter.Serialize
生成的数据。一个Excel文件不符合这一要求。
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.
为了实际解析二进制形式Excel工作簿到C#对象,你将不得不使用可以做到这一点,如的 EPPlus :
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;
}
}