用c#下载excel文件

本文关键字:文件 excel 下载 | 更新日期: 2023-09-27 18:03:58

我写了一个excel互操作代码来生成excel表格报告。报告将生成并保存在一个文件夹中。在此之后,我想下载相同的文件,我已经在相同的应用程序中编写了一个用于下载的代码。文件格式为。xlsx。下载时出现以下错误:

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

但是如果我直接进入驱动器,我可以打开相同的文件。

<<p> 下载代码/strong>:
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.");
    }
}
有人能帮我解决这个问题吗?

用c#下载excel文件

你可以试试下面的代码

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