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了.
//暂时的解决方法: 文件传输时要压缩.