Generate data dalam gridview menjadi data excell(.xls) atau pdf sangat mudah sekali dengan menggunakan library iTextSharp caranya seperti ini :
1. Daftarkan dulu library iTextSharp dalam Project References
2. cara penggunaannya seperti ini
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
3. Untuk generate dari gridview menjadi file xls seperti ini
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);
GridView1.AllowPaging = false;
GridView1.DataBind();
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @" .textmode {mso-number-format:\@; } ";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Ada beberapa error ketika menggunakan library ini diantaranya :
1. Jika gridview diletakan di dalam ascx(control) dan bukan di halaman aspx maka akan muncul error “GridView must be placed inside a form tag with runat=server”.
tetapi itu bisa dihindari dengan cara memasukan kode :
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
atau
public override void VerifyRenderingInServerForm(Control control)
{
if (control != this.gridViewControl) {
base.VerifyRenderingInServerForm(control);
}
}
2. Kadang muncul error seperti ini “RegisterForEventValidation can only be called during Render();” cara mengatasinya adalah dengan code seperti dibawah .
protected void Page_PreInit(object sender, EventArgs e)
{
Page.EnableEventValidation = false;
}
Semoga Bermanfaat.