我正在使用一种接受数据表并将其转换为 CSV 的方法。问题是,(1)当我尝试调用此方法时,将永远不会执行后续的进程/命令。(2)调用此方法后,调用表单中的列表框内容也被清除了。谁能帮我解决这个问题?我已包含以下方法以供参考。
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();
}