Home » excel » asp.net – Download excel file in C#

asp.net – Download excel file in C#

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have written an excel interop code to generate excel sheet report.The Report is generated and saved in a folder. After this I want to download the same file and I have written a code in the same application for downloading. File format is .xlsx. I am getting the following the error while downloading.

Cannot open the file, file fotmat may be different or file may be corrected.

But if I go to the drive directly I can open the same file.

downloading code:

private void DownloadFile(string getpathfromappconfig, string FileName)
{
    string path = @getpathfromappconfig + "\" + FileName + ".xlsx";
    System.IO.FileInfo file = new System.IO.FileInfo(path);
    string Outgoingfile = FileName + ".xlsx"; 
    if (file.Exists)
    { 
        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.WriteFile(file.FullName);

    }
    else
    {
        Response.Write("This file does not exist.");
    }

}

Can somebody help me to solve this?

How to&Answers:

You can try with this code

Response.ContentType = "application/vnd.ms-excel"

Replace this

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

Or you can try with this code

            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open("YourFile.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


            //your treatment ...

            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            //Clean your objects