在C#中下载excel文件

时间:2013-03-15 10:32:00

标签: c# asp.net excel interop

我编写了一个excel互操作代码来生成Excel工作表报告。生成报告并保存在一个文件夹中。在此之后,我想下载相同的文件,并在同一个应用程序中编写了一个代码供下载。文件格式为.xlsx。我在下载时遇到以下错误。

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

但如果我直接去驱动器,我可以打开同一个文件。

下载代码

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.");
    }

}

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码

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

替换此

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

或者您可以尝试使用此代码

            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