我正在使用C#導出數據到Excel。這首先運行良好。通過按鈕事件觸發導出,如果用戶從一行中的同一頁面請求多個導出,我將開始接收錯誤「無法讀取文件」。如果我選擇「保存」文件而不是打開,那麼它將文件寫入很好。它只是不會在瀏覽器中打開文件。無法讀取文件導出到Excel中的C#
我相當肯定,錯誤來自Excel,因爲Excel打開但不會加載我的文件。
我讀了Response.End和Response.Close ...有人說永遠不要用他們說一些話來使用它們。我已經嘗試過每一個End和Close的組合。
我的直覺認爲,某些內容被緩存在內存中,因爲我關閉了瀏覽器(或等待了很長時間),似乎清除了問題。
有沒有人有什麼可能是錯的想法,或者至少我怎麼知道爲什麼excel無法讀取我的文件,當我可以寫它,並從我的硬盤驅動器打開它沒有問題?
protected void btnSaveToXls_Click(object sender, EventArgs e)
{
Response.ClearHeaders();
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.Buffer = true;
Response.AddHeader("content-transfer-encoding", "binary");
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=myFileName.xls");
Response.AddHeader("pragma", "private");
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
// The main purpose of these next two writes are to name the worksheet and add the gridlines to the excel sheet
sw.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">");
sw.Write(@"<head>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Clients Contacted</x:Name>
<x:WorksheetOptions>
<x:Panes></x:Panes>
<x:Print><x:Gridlines /></x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
</head>");
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Label newLine = new Label();
newLine.Text = "<br/>";
GridView gv = new GridView();
gv.GridLines = GridLines.Both;
gv.HeaderStyle.Font.Bold = true;
//. . .
// a bunch of code here to populate my gridview
//. . .
Panel p = new Panel();
p.Controls.Add(lblTitle);
p.Controls.Add(new Label { Text = "<BR/>" });
p.Controls.Add(lblReportTitle);
p.Controls.Add(new Label { Text = "<BR/>" });
p.Controls.Add(new Label { Text = string.Format("Run Date {0}", DateTime.Now.ToString("MM/dd/yyyy")) });
p.Controls.Add(new Label { Text = "<BR/>" });
p.Controls.Add(new Label { Text = "<BR/>" });
p.Controls.Add(gv);
p.RenderControl(htw);
try
{
// Response.Clear();
sw.Write("</html>");
Response.Buffer = true;
Response.Output.Write(sw.ToString());
// Response.Output.Flush();
Response.Flush();
// Response.End();
}
catch (Exception ex)
{
//... Logging the error ...
}
finally
{
Response.Close();
}
}
}
}
正確格式化您的附件,例如嘗試使用這種格式的語法而不使用string.Format函數。 'Response.AddHeader「Content-Disposition」,「attachment; filename = myFileName.xls」' – MethodMan
@MethodMan Ok。我採納了你的建議,並確保我的例子有效。在切出位之前,爲了使示例更短並出於安全原因,更新的代碼仍然存在相同的問題。 – rnesolydev