Search code examples
asp.net-mvcexport-to-excel

ASP.NET MVC open a Excel file on click of button


I display a table with data on the page and then when user clicks Export I put the data in the excel file. Now I want to open this file so that user can save it or just view it. This is the code I have. It prompts the user to save a file but that file is the whole page!! WHat is wrong here?

   string filename = filePath.Substring(12);
                        System.IO.File.Copy(filePath, "C:/Work/MCTestSuiteCertificate/TS.ToDoViewer/Content/" + filename, true);
                        Response.Clear();
                        Response.ContentType = @"application\xls";
                       // FileInfo file = new FileInfo(Server.MapPath("~/Content/" + filename));
                        Response.AddHeader("Filename", filename);
                        Response.ContentType = "application/xls";
                        Response.TransmitFile("C:/Work/MCTestSuiteCertificate/TS.ToDoViewer/Content/" + filename);
                        //Response.WriteFile(file.FullName);
                        Response.Flush();

Solution

  • Use File method (which returns FileResult). You should not work directly with Response in MVC application.

    public ActionResult YourAction()
    {
        ...
        string filename = filePath.Substring(12);
        return File(Path.Combine(@"C:\Work\MCTestSuiteCertificate\TS.ToDoViewer\Content", filename), "application/xls");
    }
    

    PS Also please note use of Path.Combine instead of string concatenation.