//button click event
protected void btn_show_GridReport_Click(object sender, EventArgs
e)
{
DataTable dt= new DataTable();
dt=//get data from database or other sources
ExportTOExcel(dt);
}
//export to excel
public void ExportTOExcel(DataTable
dtExport)
{
string
name = "Fxportedfilename_" + DateTime.Now.ToString("ddMMyyyy_hhmmss")
+ ".xls";
HttpResponse
response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
System.Text.StringBuilder
sbb = new System.Text.StringBuilder();
sbb.Append("<html>");
//Header
information...........................................
int
Rcount = dtExport.Rows.Count;
int
Ccount = dtExport.Columns.Count;
sbb.Append("<Table
border= '1'>");
//write top
header
sbb.Append("<tr
>");
sbb.Append("<td
colspan='9' align='center' valign= 'top'
style='background-color:#00CC99; font-size:20px; '><b>");
sbb.Append("Report");
sbb.Append("</b></td>");
sbb.Append("</tr>");
//write Header
sbb.Append("<tr>");
for (int c = 0; c < Ccount; c++)
{
sbb.Append("<td>
<b>" + dtExport.Columns[c].ColumnName + "</b> </td>");
}
sbb.Append("</tr>");
//Write
Content
for (int r = 0; r < Rcount; r++)
{
sbb.Append("<tr>");
for
(int c = 0; c < Ccount; c++)
{
sbb.Append("<td> " +
dtExport.Rows[r][c].ToString()+ "</td>");
}
sbb.Append("</tr>");
}
sbb.Append("</tr
>");
sbb.Append("</Table>");
sbb.Append("</html>");
response.Write(sbb.ToString());
response.End();
return;
}
No comments:
Post a Comment