Excel File opening in browser not calling Excel

后端 未结 2 1559
别跟我提以往
别跟我提以往 2021-01-28 12:23

I am calling a function to return an Excel file and it is not opening in Excel, instead it is opening another tab in the browser. Here is my view:

 @model Inven         


        
相关标签:
2条回答
  • 2021-01-28 12:41

    Check your default program for opening csv files and set it to Excel.

    0 讨论(0)
  • Your code doesn't create an Excel file, it creates a CSV file. The content type isn't Excel-specific either. A browser may decide that Excel is the appropriate application to open this text file or not.

    Even if the browser selects Excel, opening the file may fail, eg if the client's locale uses , as a decimal separator. This is common in European countries. In this case Excel expect ; as the field separator and may open the CSV as a single text block.

    Instead of trying to trick the browser into opening a CSV in Excel, create a real Excel file using a library like EPPlus. EPPlus is available as a Nuget package so it's very easy to add it to your project.

    The library's documentation contains an article on how to use it in Web applications. Once you remove the formatting code from the example, the code is very simple:

       private void DumpExcel(DataTable tbl)
        {
            using (ExcelPackage pck = new ExcelPackage())
            {
                //Create the worksheet
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
    
                //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                ws.Cells["A1"].LoadFromDataTable(tbl, true);
    
    
                //Write it back to the client
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
                Response.BinaryWrite(pck.GetAsByteArray());
            }
        }
    

    Excel files are compressed which means that sending the file to the client will be a lot faster, especially for large files

    0 讨论(0)
提交回复
热议问题