// page load event u can use other events
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password=");
SqlCommand sqlCmd1 = new SqlCommand();
sqlCmd1.Connection = con;
sqlCmd1.CommandType = CommandType.Text;
sqlCmd1.CommandText = "select * from Table";
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd1);
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Export ex = new Export();
ex.Convert(ds, Response);
}
}
// create a class say Export.cs
public class Export
{
public Export()
{
//
// TODO: Add constructor logic here
//
}
public void Convert(DataSet ds, HttpResponse response)
{
//*********Export to Excel/Doc**************
//first let's clean up the response.object
response.Clear();
response.Charset = "";
//set the response mime type for excel
// response.ContentType = "application/vnd.ms-excel"; // excel export
response.ContentType = "application/msword"; // doc export
//create a string writer
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
//create an htmltextwriter which uses the stringwriter
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//instantiate a datagrid
DataGrid dg = new DataGrid();
//set the datagrid datasource to the dataset passed in
dg.DataSource = ds.Tables[0];
//bind the datagrid
dg.DataBind();
//tell the datagrid to render itself to our htmltextwriter
dg.RenderControl(htmlWrite);
//all that's left is to output the html
response.Write(stringWrite.ToString());
response.End();
}
}