gpt4 book ai didi

c# - 用C#下载excel文件

转载 作者:行者123 更新时间:2023-12-04 22:08:24 34 4
gpt4 key购买 nike

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

}

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

最佳答案

您可以尝试使用此代码

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

关于c# - 用C#下载excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430051/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com