将字节数组保存到excel文件

时间:2013-10-11 09:30:18

标签: c# asp.net io

我从ssrs报告中获取了一个字节数组。然后我想将它保存在服务器上的Excel中以便进一步处理。 我可以在客户端浏览器上导出它但是当尝试将文件保存在服务器上时它会保存。但是在打开“excel无法打开文件因为文件格式或文件扩展名无效”时给出了错误。

代码如下

Microsoft.Reporting.WebForms.ReportViewer rview = new Microsoft.Reporting.WebForms.ReportViewer();
//Web Address of your report server (ex: http://rserver/reportserver)

rview.ServerReport.ReportServerUrl = new Uri("http://rserver/reportserver");

rview.ServerReport.ReportPath = "/Report Project2/Comment";

string mimeType, encoding, extension, deviceInfo;
string[] streamids;
Microsoft.Reporting.WebForms.Warning[] warnings;
string format = "Excel"; //Desired format goes here (PDF, Excel, or Image)

deviceInfo = "<DeviceInfo>" + "<SimplePageHeaders>True</SimplePageHeaders>" + "</DeviceInfo>";
byte[] bytes = rview.ServerReport.Render(format, deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);

try
{         
    System.IO.FileStream _FileStream = new System.IO.FileStream(Server.MapPath("output.xlsx"), System.IO.FileMode.Create, System.IO.FileAccess.Write);  
    _FileStream.Write(bytes, 0, bytes.Length);   
    //_FileStream.Close(); 
}
catch (Exception _Exception)
{
    Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}

它不知道如何使用与Respose对象一起使用的infor格式,deviceInfo等在客户端浏览器上保存excel。

这是我如何写入Response object.It工作正常的gor响应对象。

Response.Clear();
            if (format == "PDF")
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-disposition", "filename=output.pdf");
            }
            else if (format == "Excel")
            {
                Response.ContentType = "application/excel";
                Response.AddHeader("Content-disposition", "filename=output.xls");
            }
            Response.OutputStream.Write(bytes, 0, bytes.Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
            Response.Flush();
            Response.Close();

1 个答案:

答案 0 :(得分:0)

请将扩展名更改为xls。 xlsx扩展名用于格式EXCELOPENXML,xls格式用于EXCEL

相关问题