快速导出CSV
快速导出CSV
protected void btnQuery_Click(object sender, EventArgs e)
{
try
{
DataTable dt = _bll.GetCompanys(this.txtBegin.Text, this.txtEnd.Text);
//DataTableToCSV(columns, dt);
string data = Export(dt);
string temp = string.Format("attachment;filename={0}", "ExportData.csv");
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ClearHeaders();
Response.AppendHeader("Content-disposition", temp);
Response.Write(data);
Response.End();
}
catch
{
}
}
public string Export(DataTable data)
{
string csvString = string.Empty;
foreach (DataColumn title in data.Columns)
{
csvString += GetContent(title.ColumnName) + ",";
}
csvString = csvString.TrimEnd(',') + Environment.NewLine;
foreach (DataRow row in data.Rows)
{
foreach (DataColumn column in data.Columns)
{
csvString += GetContent(row[column]) + ",";
}
csvString = csvString.TrimEnd(',') + Environment.NewLine;
}
return csvString;
}
private string GetContent(object text)
{
if (text == null || text == Convert.DBNull) return "";
string str = text.ToString().Replace("\"", "\"\"");
str = str.IndexOf(',') == -1 ? str : string.Format("\"{0}\"", str);
return str;
}