using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
namespace Export_Excel_With_Header_Color
{
public partial class _Default : System.Web.UI.Page
{
MySqlConnection ObjCon = new MySqlConnection("server=localhost;user id=root;Password=admin;database=college");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
MySqlDataAdapter ObjAda = new MySqlDataAdapter("Select * from rank",ObjCon);
ObjAda.Fill(dt);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.xls");
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.Write("<font style='font-size:20.0pt; font-family:Calibri;'>");
HttpContext.Current.Response.Write("<BR><BR><BR>");
HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' borderColor='#000000' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
int columnscount = dt.Columns.Count;
for (int j = 0; j < columnscount; j++)
{
HttpContext.Current.Response.Write("<Td style='background-color:Blue'>");
HttpContext.Current.Response.Write("<B>");
HttpContext.Current.Response.Write(dt.Columns[j].ColumnName.ToUpper());
HttpContext.Current.Response.Write("</B>");
HttpContext.Current.Response.Write("</Td>");
}
foreach (DataRow row in dt.Rows)
{
HttpContext.Current.Response.Write("<TR>");
for (int i = 0; i < dt.Columns.Count; i++)
{
HttpContext.Current.Response.Write("<Td style='width:150px'>");
HttpContext.Current.Response.Write(row[i].ToString());
HttpContext.Current.Response.Write("</Td>");
}
HttpContext.Current.Response.Write("</TR>");
}
HttpContext.Current.Response.Write("</Table>");
HttpContext.Current.Response.Write("</font>");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}