Byte数组到Excel工作簿 [英] Byte array to excel workbook

查看:755
本文介绍了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;
    }
}

这篇关于Byte数组到Excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆