在mvc中下载文件最直接的方法

时间:2016-12-13 14:50:38

标签: asp.net asp.net-mvc

我目前正在我的c盘上保存一个excel文件。

    public ActionResult Export()
    {
        try
        {
            Excel.Application application = new Excel.Application();
            Excel.Workbook workbook = application.Workbooks.Add(System.Reflection.Missing.Value);
            Excel.Worksheet worksheet = workbook.ActiveSheet;
            var people = db.People.ToList();
            worksheet.Cells[1, 1] = "Last Name";
            worksheet.Cells[1, 2] = "First Name";
            int row = 2;
            foreach (var person in people)
            {
                worksheet.Cells[row, 1] = person.PersonFName;
                worksheet.Cells[row, 2] = person.PersonLName;
                row++;
            }
            workbook.SaveAs("c:\\test\\worksheet.xls");
            workbook.Close();
            Marshal.ReleaseComObject(workbook);

            application.Quit();
            Marshal.FinalReleaseComObject(application);
            ViewBag.Result = "Done";
        }
        catch(Exception ex)
        {
            ViewBag.Result = ex.Message;

        }

       return File("c:\\test\\workseet.xls", "application/vnd.ms-excel", "workseet.xls");


       // return View("Success");
    }

我可以去c:\\test\workseet.xls并且它存在于那里我可以用它做任何事情......

我想要从返回视图转换我的方法以返回文件下载...

我认为这很简单:

    return File("c:\\test\\workseet.xls", "application/vnd.ms-excel", "workseet.xls");

但是,当我执行此方法并单击要下载的链接时,它会给我这个错误。

The process cannot access the file 'c:\test\workseet.xls' because it is being used by another process.

1 个答案:

答案 0 :(得分:2)

This duplicate question只是展示如何使用EPPlus以可扩展的方式在服务器端生成Excel文件的其中一个。它实际上比使用Excel互操作更容易,速度更快。您甚至不必将文件保存到磁盘。

public ActionResult ExportData()
{

    //Somehow, load data to a DataTable

    using (ExcelPackage package = new ExcelPackage())
    {
        var ws = package.Workbook.Worksheets.Add("My Sheet");
        //true generates headers
        ws.Cells["A1"].LoadFromDataTable(dataTable, true);

        //Save the workbook to a stream
        var stream = new MemoryStream();
        package.SaveAs(stream);

        string fileName = "myfilename.xlsx";
        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        stream.Position = 0;
        return File(stream, contentType, fileName);
    }
}

您可以使用LoadFromDataTable填充数据表中的工作表,或使用LoadFromCollection来加载集合中的数据,例如List<Sale>

两种方法都返回一个ExcelRange对象(一系列单元格),您可以使用它来格式化单个单元格,行和列。您还可以从范围创建表并应用主题。

副本更进一步,并展示了如何avoid even the MemoryStream