Export csv

Posted on 2011-12-09 14:51  Leon0812  阅读(219)  评论(0编辑  收藏  举报
public void CreateCSV(DataTable dt, string fileName, HttpContext context)
{

StringBuilder csvDoc = new StringBuilder();
string strTitle = string.Empty;
for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
strTitle += "\"" + dt.Columns[i].ColumnName + "\"";
strTitle += ",";
}
strTitle.Substring(0,strTitle.Length-1);
csvDoc.AppendLine(strTitle);


string strValue = string.Empty;
foreach (DataRow dr in dt.Rows)
{
strValue = string.Empty;
for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
strValue+=("\"" + dr[i].ToString().Replace("'", "''").Replace(",", "") + "\"");
strValue += (",");
}
strValue.Substring(0,strValue.Length - 1);
csvDoc.AppendLine(strValue);
}



byte[] strdata = System.Text.Encoding.Default.GetBytes(csvDoc.ToString());

context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
context.Response.BinaryWrite(strdata);
context.Response.Flush();
context.Response.End();



}

Copyright © 2024 Leon0812
Powered by .NET 9.0 on Kubernetes