The Below code makes you more understand how can we export the Dataset values to an Excel Sheet
Initially we use the DataGridView to get the Data by Command Object. We then Create the DataSet and fil the Dataset with the Data we got from the DataGridView. Then we provide the button, By which clicking on that we can export the Data to the Excelsheet
Below code show you how to write a code for exporting
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
PrepareForExport(GridView1);
Table tb = new Table();
TableRow tr1 = new TableRow();
TableCell cell1 = new TableCell();
cell1.Controls.Add(GridView1);
tr1.Cells.Add(cell1);
TableCell cell2 = new TableCell();
cell2.Text = " ";
if (rbPreference.SelectedValue == "2")
{
tr1.Cells.Add(cell2);
tb.Rows.Add(tr1);
}
else
{
TableRow tr2 = new TableRow();
tr2.Cells.Add(cell2);
TableRow tr3 = new TableRow();
tb.Rows.Add(tr1);
tb.Rows.Add(tr2);
tb.Rows.Add(tr3);
}
tb.RenderControl(hw);
//style to format numbers to string
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
No comments:
Post a Comment