在C#中下载excel文件
我已经写了一个excel的互操作代码来生成excel工作表report.The报告生成并保存在一个文件夹。 在此之后,我想下载相同的文件,并且我已经在同一个应用程序中编写了一个代码进行下载。 文件格式是.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."); } }
有人可以帮我解决这个问题吗?
你可以试试这个代码
Response.ContentType = "application/vnd.ms-excel"
replace这个
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