如何解决将 Excel 文件保存到用户桌面时出现的问题?

How to fix issue when saving Excel file to users desktop?

正在尝试将 excel 文件从 c# asp.net 网络应用程序保存到用户桌面。这在测试时在本地机器上运行良好,但在远程服务器上却不行。有人可以帮我解决这个问题吗?谢谢!

代码:

string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
FileInfo fi = new FileInfo(filePath + @"\spreadsheet.xlsx");
excelPackage.SaveAs(fi);

错误:

看起来您可能正在使用 EPPplus (excelPackage.SaveAs(fi);)。因此,如果您使用 asp.net 作为您的标记,您可以将 Excel 文件发送到浏览器,用户将获得一个保存文件对话框。

//convert the excel package to a byte array
byte[] bin = excelPackage.GetAsByteArray();

//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;

//set the correct contenttype
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());

//set the filename for the excel package
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");

//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);

//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();