/// <summary>
/// 导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExport_Click(object sender, EventArgs e)
{
//清除缓冲区
Response.ClearContent();
//添加相应报文头
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlDecode("人员信息.xls"));
//设置文件格式
Response.ContentType = "application/excel";
//设置编码
Response.ContentEncoding = Encoding.UTF8;
//向缓冲区写入内容
Response.Write(GetGridTableHtml(GridUserList));
Response.End();
}
//拼 html table
public string GetGridTableHtml(Grid grid)
{
StringBuilder sb = new StringBuilder();
sb.Append("<meta http-equiv=“content-type” content=“application/excel; charset=UTF-8”/>");
sb.Append("<table cellspacing=“0” rules=“all” border=“1” style=“border-collapse:collapse;”>");
sb.Append("");
foreach (GridColumn column in grid.Columns)
{
if (column.ColumnIndex != 5)
sb.AppendFormat("{0}", column.HeaderText);
}
sb.Append("");
//根据查询后的数据重新绑定数据,不分页
var dataList = GetNoPagedList();
GridUserList.DataSource = dataList;
GridUserList.DataBind();
string lastValue = "", value = "";
foreach (GridRow row in grid.Rows)
{
sb.Append("<tr>");
foreach (GridColumn column in grid.Columns)
{
if (column.ColumnIndex == 5)
continue;
if (column.ColumnIndex == 0)
{
sb.AppendFormat("<td>{0}</td>", row.RowIndex + 1);
}
else if (column.ColumnIndex == 1) //第1列,所属单位
{
value = (row.FindControl("lable") as System.Web.UI.WebControls.Label).Text;
if (lastValue == value) //不渲染此单元格
{
continue;
}
else
{
lastValue = value;
}
int rowspan = dataList.Where(d => GetDepFullName(d.DepartmentID) == value).Count();
sb.AppendFormat("<td rowspan='" + rowspan + "'>{0}</td>", value);
}
else
{
string html = row.Values[column.ColumnIndex].ToString();
sb.AppendFormat("<td>{0}</td>", html);
}
}
sb.Append("</tr>");
}
sb.Append("</table>");
return sb.ToString();
}