使用Webforms和EPPlus下载文件 [英] Downloading a file with webforms and EPPlus

查看:72
本文介绍了使用Webforms和EPPlus下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为旧版Webforms应用程序实现小型导出功能.

I am implementing a small export feature for a legacy webforms application.

我现在的导出代码只是标头(只是测试我可以成功创建文件的标头):

My export code right now is only headers (just testing the that I can successfully create a file):

public MemoryStream Export()
{
    var result = new MemoryStream();
    using (var p = new ExcelPackage())
    {
        var ws = p.Workbook.Worksheets.Add("Contacts");
        var col = 1;
        ws.Cells[1, col++].Value = "ID";
        ws.Cells[1, col++].Value = "First Name";
        ws.Cells[1, col++].Value = "Last Name";
        ws.Cells[1, col++].Value = "Email";
        ws.Cells[1, col++].Value = "Phone";
        ws.Cells[1, col++].Value = "Address";
        p.SaveAs(result);
    }

    return result;
}

这是按钮处理程序:

var ms = Export();
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=Contacts_{DateTime.Now:yyyyMMddhhmmss}.xlsx");
HttpContext.Current.Response.StatusCode = 200;
// HttpContext.Current.Response.End();

一个问题是,我找到的所有示例在方法末尾都有HttpContext.Current.Response.End()调用,但是如果执行此操作,则会引发异常.注释掉该行似乎不错,但这将我引到我的主要问题:保存文件然后在excel中打开时,Excel抱怨文件存在问题.我的印象是EPPlus可以制作格式正确的文件,那么我还缺少什么?

So one issue is that all the examples I find have the HttpContext.Current.Response.End() call at the end of the method, but if I do this, it throws an exception. Commenting this line out seems to work fine but that leads me to my main problem: when the file is saved and then opened in excel, Excel complains there is a problem with the file. My impression is that EPPlus makes well formed files, so what am I missing?

更新#1 我尝试直接将EPPlus软件包保存到磁盘.这似乎没有问题.因此问题出在将程序包写入内存流和返回结果之间的某个地方.

Update #1 I tried directly saving the EPPlus package to disk. That seems to work without issue. So the problem lies somewhere between writing the package to the memorystream and returning the result.

推荐答案

以下是对我有用的代码

var ms = Export();
Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=Contacts_{DateTime.Now:yyyyMMddhhmmss}.xlsx");
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.BinaryWrite(ms.ToArray());
Response.End();

这篇关于使用Webforms和EPPlus下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆