将字节数组保存到Excel文件

问题描述 投票:0回答:1

我从 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 对象一起使用的信息格式、deviceInfo 等在客户端浏览器上保存 excel。

这是我写入响应对象的方式。响应对象工作正常。

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();
c# asp.net io
1个回答
0
投票

请将扩展名更改为xls。 xlsx 扩展名适用于 EXCELOPENXML 格式,而 xls 则适用于 EXCEL 中的格式

© www.soinside.com 2019 - 2024. All rights reserved.