导出到Excel(无模板)

  /// <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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值