I have this void to export a GridView rows to Excel and it works fine:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable tbl = GridView1.DataSource as DataTable;
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string fileName = "ConsultaSerialesFinishGoods_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ".xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
GridView1.HeaderRow.Cells[0].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[1].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[2].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[3].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[4].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[5].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[6].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[7].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[8].BackColor = Color.Blue;
GridView1.HeaderRow.Cells[9].BackColor = Color.Blue;
GridView1.HeaderRow.ForeColor = Color.White;
GridView1.AlternatingRowStyle.Reset();
GridView1.RowStyle.Reset();
GridView1.BackColor = Color.Transparent;
GridView1.GridLines = GridLines.Both; //Si queremos que el excel tenga lineas
GridView1.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
Also I have this other JS function to hide rows from the GridView1 using a Textbox:
function Search_Gridview(strKey) {
var strData = strKey.value.toLowerCase().split(" ");
var tblData = document.getElementById("<%=GridView1.ClientID %>");
var rowData;
for (var i = 1; i < tblData.rows.length; i++) {
rowData = tblData.rows[i].innerHTML;
var styleDisplay = 'none';
for (var j = 0; j < strData.length; j++) {
if (rowData.toLowerCase().indexOf(strData[j]) >= 0)
styleDisplay = '';
else {
styleDisplay = 'none';
break;
}
}
tblData.rows[i].style.display = styleDisplay;
}
}
I want to avoid export the hidden rows (when they are hidden using the textbox with the JS), because the Button2 is exporting all the Rows of the GridView even the hidden rows.
Do you know how can I do that? Thank you.