protected void Button1_ServerClick(object sender, EventArgs e)
{
DataTable dtnew = null;
try
{
string filename = "Detail.csv";
dtnew = YourDataTable.DefaultView.ToTable();
// if column detail of YourDataTable contain xml data then
if (dtnew != null && dtnew.Rows.Count > 0)
{
foreach (DataRow dr in dtnew.Rows)
{
dr["detail"] = Common.MyCStr(dr["detail"]).Replace("<", "<");
dr["detail"] = Common.MyCStr(dr["detail"]).Replace(">", ">");
dr["detail"] = Common.MyCStr(dr["detail"]).Replace(Environment.NewLine,"");
dr["detail"] = Common.MyCStr(dr["detail"]).Replace("\n", "");
}
}
string csv = ToCSV(dtnew);
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.AddHeader("Content-Length", csv.Length.ToString());
Response.Write(csv);
Response.End();
}
catch (OutOfMemoryException oex)
{
lblError.Text = "Sorry!Data is too large to export";
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
public static string ToCSV(DataTable table)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
No comments:
Post a Comment