[英]export datatable to CSV with Save File Dialog box - C#
努力讓我的CSV導出顯示“保存文件”對話框。 它保存到文件ok,但不允許用戶保存。 任何人都可以看到我的代碼可能出錯嗎?
string filename = Server.MapPath("~/download.csv");
StreamWriter sw = new StreamWriter(filename, false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
Response.Clear();
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv");
Response.WriteFile(filename);
Response.Flush();
Response.End();
我想到了內容處理行,它提出了對話框,但也許還有其他我需要做的事情。
謝謝
啊,已經發現問題是什么......
我在更新面板中有按鈕,但沒有意識到響應對象在更新面板中不起作用。
我將下載按鈕設為觸發器,現在效果很好。
<Triggers>
<asp:PostBackTrigger ControlID="btnDownload" />
</Triggers>
無論如何,謝謝你的建議
我很確定你需要
Response.Write()
后
Response.End()
您可以嘗試在Response.Clear()
調用后清除內容和標題:
Response.ClearContent();
Response.ClearHeaders();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.