1

我编写了一个 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.");
    }

}

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

4

1 回答 1

3

您可以尝试使用此代码

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
于 2013-03-15T10:37:40.443 回答