我正在尝试从代码中保存excel文件并将其下载给用户。
创建文件的代码:
Excel.Application ExcelObj = new Excel1.Application();
Excel.Workbook wb = ExcelObj.Workbooks.Add();
Excel.Worksheet wsh = wb.ActiveSheet;
wsh.Cells[1, 1] =".....";
//fill data in the file
string errorsFileName = "Error.xls";
string url = @"..." + errorsFileName;
wb.SaveAs(url);
wb.Close();
创建后,我可以从他的位置打开文件。 保存得很好。
下一步是将文件下载到用户,我使用此代码(在不同的情况下适用于我)!:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
//response.ContentType = "text/plain";
response.ContentType = "application/ms-excel";
response.ContentEncoding = System.Text.Encoding.Default;
response.BinaryWrite(System.Text.Encoding.Default.GetPreamble());
response.Charset = "";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
response.TransmitFile(url);
response.Flush();
下载完成,但下载的文件包含Gibberish ...
是什么导致它?