我正在使用EPPlus库将数据写入Excel。我希望能够在HTTP响应对象中编写好的内容并将其发送,以便客户端然后获取文件另存为对话框并可以选择保存文件的位置。
到目前为止,在网上搜索了很多,我仍然没有成功,继承我的代码片段 -
我试过了 -
using (ExcelPackage package = new ExcelPackage())
{
//Writing data to the worksheet
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=file.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
所有在线链接都显示相同的代码,但这仍然无效。也没有客户端或服务器端错误。
有什么想法吗?
编辑:所以如果这段代码有效,客户端可能会遇到一些调用此代码的问题?我对请求响应模型没有多少经验,我很有可能搞砸了。
我发了一个帖子请求,其中包含要写入文件的内容 -
$post("/app/Services/ExcelDownloadHandler.ashx", { "columnValues": columnValues });
在ExcelDownloadHandler.ashx中,我有
public void ProcessRequest(HttpContext context)
{
var r = context.Response;
Models.DTData excelData = (Models.DTData)Newtonsoft.Json.JsonConvert.DeserializeObject(context.Request.Form["columnValues"], typeof(Models.DTData));
//Write excelData to worksheet using EPPlus
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=file.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
//一旦我对响应做了二进制写操作,我应该在浏览器上获取文件保存对话框,这是正确的吗?
我遇到了同样的问题。添加此处显示的四条注释行会显示提示,允许用户在IE11中打开,保存或另存为。
//Write it back to the client
Response.ClearContent(); //Clear contents of current Response.
Response.BufferOutput = true; //Buffer output before sending.
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExportData.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.Flush(); //Send buffered output to client.
Response.End(); //Stop rqst. process; Raise EndRequest event.
我使用EPPLUS像下面的代码:
MemoryStream ms = new MemoryStream();
pkg.SaveAs(ms);
byte[] ba = ms.GetBuffer();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement; filename=ExportData.xlsx");
HttpContext.Current.Response.AddHeader("Content-Length", ba.Length.ToString());
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.BinaryWrite(ba);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();