Question

I am trying to open an excel file on local disk in Excel using the FileResult object. When i click the file to open, it downloads the file which is named the same as my ActionResult(WTF?), and it brings up the "choose program" window when i click the downloaded file. If i choose Excel, it'll open it but what am i missing to make it download as an excel file and open it without the extra steps? Below is my switch statement for opening files. Thanks

public ActionResult GetFile(string path)
    {

        string extension = new FileInfo(path).Extension;
        if (extension != null || extension != string.Empty)
        {
            switch (extension)
            {
                case ".pdf":
                    return File(path, "application/pdf");
                case ".txt":
                    return File(path, "application/plain");
                case ".jpeg":
                    return File(path, "application/jpeg");
                case ".doc":
                    return File(path, "application/msword");
                case ".docx":
                    return File(path, "application/msword");
                case ".xls":
                    return File(path, "application/msexcel");
                case ".xlsx":
                    return File(path, "application/msexcel");
                default:
                    return File(path, "application/octet-stream");
            }
        }
        return View("Index");
    }
Was it helpful?

Solution

Check this:

 case ".xls":
    return File(path, "application/vnd.ms-excel");
 case ".xlsx":
   return File(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

Extra info

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top