从数据表写入http响应的CSV数据在C#中丢失

时间:2016-06-06 12:15:42

标签: c# csv httpresponse outputstream

我正在将一些csv数据写入http响应中。此数据正从数据库提取到数据表中,然后使用streamwriter写入http响应内容。 问题是在客户端下载的CSV文件不包含所有数据。它始终缺少文件末尾的一些数据。以下是代码段:

System.Web.HttpResponse Response

Response.AddHeader("content-disposition","attachment; filename=Results.csv");
Response.AddHeader("content-type","text/plain");

writeCsvDataStream_ss(new StreamWriter(Response.OutputStream), dt);
Response.End();

private void writeCsvDataStream_ss(StreamWriter Response, DataTable myDT)
{
    StringBuilder result = new StringBuilder();
    if (myDT.Rows.Count == 0)
    {
        Response.Write("No Data available for selected ESIID");
        Response.Flush();
        return;
    }
    for (int i = 0; i <  myDT.Columns.Count; i++) 
    { result.Append(myDT.Columns[i].ColumnName); 
      result.Append(i == myDT.Columns.Count - 1 ? "\n" : ","); 
    }
    foreach (DataRow row in myDT.Rows) 
    { 
        for (int i = 0; i <  myDT.Columns.Count; i++) 
        { result.Append(row[i].ToString()); 
          result.Append(i == myDT.Columns.Count - 1 ? "\n" : ","); 
        } 
    }
    Response.Write(result.ToString());
}

我尝试过很多东西,但没有任何效果。请有人帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:0)

private void writeCsvDataStream_ss(StreamWriter Response, DataTable dt)
{
   StringBuilder sbCsv ;
   for (int i = 0; i < dt.Rows.Count; i++)
   {
          sbCsv = new StringBuilder(1024);
          for (int j = 0; j < dt.Columns.Count; j++)
          {
                sbCsv.Append(dt.Rows[i][j] + ";");
          }
          sbCsv.Append(Environment.NewLine);
          Response.Write(sbCsv.ToString());
          if (i % 1000) == 0)
              Response.Flush();
        }
}