将 Excel 2007 读取到 Byte[], 然后再保存到新的Excel文件中, 这时打开新文件会出错....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace ExcelTest
{
    /// <summary>
    /// 将Excel 2007 读取成 Byte[]. 然后将  Byte[] 保存到另一个文件中. 测试是否出错.
    /// </summary>
    public class ExcelToByteAry_ThenSaveExcelcs
    {
        public Byte[] GetByteAry(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            Stream stream = file.OpenRead();
            stream.Position = 0;
            byte[] buffer = new byte[stream.Length + 1];
            //将文件读入字节数组
            stream.Read(buffer, 0, buffer.Length);
            stream.Close();
            return buffer;
        }

        public void SaveToFile(Byte[] byteAry, string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                    File.Delete(filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            FileStream stream = new FileStream(filePath, FileMode.CreateNew);
            //写入文件
            stream.Write(byteAry, 0, byteAry.Length);
            stream.Close();
        }
    }
}

//调用

 

        private void btnExcelToByteAry_ThenSaveExcelcs_Click(object sender, EventArgs e)
        {
            //System.IO.File.Copy(@"D:\My Documents\Visual Studio 2010\Projects\ExcelTest\ExcelTest\excel2007.xlsx",
            //    @"D:\My Documents\Visual Studio 2010\Projects\ExcelTest\ExcelTest\CopyExcel2007.xlsx");  //Copy 可以打开
            ExcelToByteAry_ThenSaveExcelcs e2b = new ExcelToByteAry_ThenSaveExcelcs();
            byte[] byteAry = e2b.GetByteAry(@"D:\My Documents\Visual Studio 2010\Projects\ExcelTest\ExcelTest\excel2007.rar");
            e2b.SaveToFile(byteAry, @"D:\My Documents\Visual Studio 2010\Projects\ExcelTest\ExcelTest\nexcel2007.rar");
        }

//打开新的Excel出错  :  发现不可读取的错误.

//如果使用File.Copy 不会出现. 但是因为 在Silverlight 中, 客户端与服务器的文件传输一般是用Byte[]. 所以不能用File.Copy了.

//暂时的解决方法: 文件传输时要压缩.

 

转载于:https://www.cnblogs.com/Ken-Cai/archive/2012/10/12/2722005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值