我正在使用接受datatable並將其轉換爲CSV的方法。問題是,(1)當我嘗試調用這個方法時,將永遠不會執行成功的進程/命令。 (2)調用該方法後清除調用表中的列表框內容。任何人都可以幫我解決這個問題嗎?我已經包括了下面的方法供參考。C#導出爲CSV問題
public void DataTableToCSV(string fileName, DataTable dt)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace(" ", "").Replace("/", "")));
Response.Charset = "";
Response.ContentType = "application/vnd.csv";
System.IO.StringWriter sWriter;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sWriter = new System.IO.StringWriter(sb);
string Str;
for (int k = 0; k <= (dt.Columns.Count - 1); k++)
{
sWriter.Write(dt.Columns[k].ColumnName + ",");
}
sWriter.WriteLine(",");
for (int i = 0; i <= (dt.Rows.Count - 1); i++)
{
for (int j = 0; j <= (dt.Columns.Count - 1); j++)
{
Str = (dt.Rows[i][j].ToString().Replace(",", ""));
if (Str == " ")
Str = "";
Str = (Str + ",");
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
Response.Write(sb.ToString());
Response.End();
}
如何調用此方法?使用ajax調用? – 2013-05-14 10:03:42
我認爲它是Asp.Net Webform? – Fendy 2013-05-14 10:03:59
[您可能會發現這有幫助!](http://secretgeek.net/csv_trouble.asp) – JMK 2013-05-14 10:14:17