public void ExportExel(DataTable data, string fileName)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
// context.Response.Charset = System.Text.UTF8Encoding.UTF8.EncodingName.ToString();
// context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
//rite column header names
for (int i = 0; i < data.Columns.Count; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(data.Columns[i].ColumnName);
}
context.Response.Write(Environment.NewLine);
//Write data
foreach (DataRow row in data.Rows)
{
for (int i = 0; i < data.Columns.Count; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(row.ItemArray[i].ToString());
}
context.Response.Write(Environment.NewLine);
}
context.Response.End();
}
// return datatable
private DataTable Test_db_table()
{
DataTable ConData = new DataTable();
con.Open();
SqlCommand com1 = new SqlCommand("select * from employee", con);
SqlDataAdapter da1 = new SqlDataAdapter(com1);
da1.Fill(ConData);
return ConData;
}
// -- execute function
protected void Button1_Click(object sender, EventArgs e)
{
ExportExe(Test_db_table(),"filename");
}
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
// context.Response.Charset = System.Text.UTF8Encoding.UTF8.EncodingName.ToString();
// context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
//rite column header names
for (int i = 0; i < data.Columns.Count; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(data.Columns[i].ColumnName);
}
context.Response.Write(Environment.NewLine);
//Write data
foreach (DataRow row in data.Rows)
{
for (int i = 0; i < data.Columns.Count; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(row.ItemArray[i].ToString());
}
context.Response.Write(Environment.NewLine);
}
context.Response.End();
}
// return datatable
private DataTable Test_db_table()
{
DataTable ConData = new DataTable();
con.Open();
SqlCommand com1 = new SqlCommand("select * from employee", con);
SqlDataAdapter da1 = new SqlDataAdapter(com1);
da1.Fill(ConData);
return ConData;
}
// -- execute function
protected void Button1_Click(object sender, EventArgs e)
{
ExportExe(Test_db_table(),"filename");
}