提示用户下载构建服务器端的excel文件

时间:2014-04-24 11:28:41

标签: c# asp.net-mvc file stream download

我有一个方法,当按下“保存按钮”时调用我的CreateAnnuityExcelSheet。

调用CreateAnnuityExcelSheet的方法:

[HttpPost]
public ActionResult ShowAnnuityPMT(FormCollection form, string SubmitValue, string     fileName)
    {
        //Code for finalList
        if (SubmitValue == "Save")
        {
            CreateAnnuityExcelSheet(finalList, form, DTCyear); //When I call this method I want the user/browser to download the Excelfile created in CreateAnnuityExcelSheet
        }
        return PartialView("ShowDetail", finalList);
    }

方法如下:

public void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear)
    {
        List<Calculation> newList = new List<Calculation>();
        newList.Add(cList.First()); //Getting the values for the first row
        var StartValue = newList[0].StartValue;
        var radio = form["advanceOrArrears"];
        string fileName = newList[0].CalculationName;
        string path = @"C:\ExcelFiles\" + fileName + ".xlsx"; //Path for the file
        FileInfo info = new FileInfo(path);
        info.Directory.Create(); //If C:\ExcelFiles does not exist, create it
        if (!info.Exists)
        {
            using (ExcelPackage package = new ExcelPackage(info))
            {
                ExcelWorksheet ws = package.Workbook.Worksheets.Add(fileName);
                //Styles for the sheet

                var stream = new MemoryStream();
                package.SaveAs(stream);
                stream.Position = 0;

                byte[] bytes = stream.GetBuffer();
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = "application/xlsx";
                Response.AddHeader("content-disposition", "attachment; filename=report.xlsx");
                Response.BinaryWrite(bytes);
                Response.Flush();
    }

主要问题是我在服务器端创建了一个excelsheet,然后想要将其发送回浏览器进行下载。如何将我的包发送回浏览器进行下载?

现在该方法返回void,我应该返回File吗?但是,如果我这样做,如何使用视图发送文件,以便用户可以开始下载Excelfile?

这是我的视图显示的内容:http://cdn.imghack.se/images/6c513c233f4ee5df36e18a428c9b8d1f.png This is what my View displays

1 个答案:

答案 0 :(得分:3)

你的行动应该返回一个ActionResult,如果你有一个流,一个简单的方法是使用FilestreamResult

请注意,有一个属性可以设置文件的名称。

return new FileStreamResult(stream, "application/vnd.ms-excel")
{
    FileDownloadName = "myfile.xslx"
};

以下是从表单发布数据并下载生成的文件的示例。

创建一个模型来保存表单值:

public class DownloadModel
{
    public int InputA { get; set; }
    public string InputB { get; set; }
}

使用两个操作创建一个控制器:一个用于显示表单(索引),另一个用于提交数据并获取文件(DownloadFile)

public class DownloadController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult DownloadFile(DownloadModel model)
    {
        // read form value via model
        System.Diagnostics.Debug.WriteLine(model.InputA);
        System.Diagnostics.Debug.WriteLine(model.InputB);

        // assume we create an an excel stream...
        MemoryStream excelStream = new MemoryStream();

        return new FileStreamResult(excelStream, "application/vnd.ms-excel")
        {
            FileDownloadName = "myfile.xslx"
        };
    }
}

将剃刀视图Download / Index.cshtml中的操作表单设置为DownloadFile操作

@model WebApp.Models.DownloadModel

@{
    ViewBag.Title = "DownloadFile";
}

<h2>DownloadFile</h2>

@using (Html.BeginForm("DownloadFile", "Download"))
{

    @Html.TextBoxFor(model => model.InputA);

    @Html.TextBoxFor(model => model.InputB);

    <input type="submit" value="Save" name="submitButton" />
}