C# Excel的导出 经典案例

来源:互联网 发布:iphone手机解压缩软件 编辑:程序博客网 时间:2024/06/06 17:02

1、下面是导出按钮事件 ,用的是Gridview控件

#region 导出选中的会员信息

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        string[] title = { "用户名", "昵称", "手机号码", "邮箱", "会员级别" };
        string th1 = "<td style=\"height:25pt; background-color:#008080; font-size:12pt; font-family:Arial; font-weight:bold; color:#ffffff; text-align:center\">{0}</td>";
        string td1 = "<td style=\"height:20pt; background-color:#ccffcc; text-align:center\">{0}</td>";
        string trToatal = string.Format("<tr>{0}{0}{0}{0}{0}</tr>", "<td style=\"height:20pt; background-color:#ccffcc\"></td>", "<td style=\"height:20pt; background-color:#ccffcc; color:#ff0000; font-weight:bold; font-size:11pt\">{0:0}</td>");
        StringBuilder builder = new StringBuilder();
        builder.Append("<html><head><meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/></head><body><table border=\"1\" bordercolor=\"#D0D7E5\">");
        builder.Append("<tr>");

        for (int j = 0; j < title.Length; j++)
        {
            builder.Append(string.Format(th1, title[j]));
        }
        builder.Append("</tr>");
        int SelectNum = 0;
        for (int i = 0; i <= gvCategory.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)gvCategory.Rows[i].FindControl("Select");
            if (cbox.Checked == true)
            {
                SelectNum = 1;
                TUser_Info userInfo = TUser_InfoRule.GetUserID(int.Parse(gvCategory.DataKeys[i].Value.ToString()));
                if (!userInfo.IsEmpty)
                {
                    userlevelrule rule = userlevelruleRule.Getlevelid(userInfo.UserType);
                    builder.Append("<tr>");
                    builder.Append(string.Format(td1, userInfo.UserLoginName));
                    builder.Append(string.Format(td1, userInfo.UserName));
                    builder.Append(string.Format(td1, userInfo.TelephoneNumber));
                    builder.Append(string.Format(td1, userInfo.UserEmail));
                    builder.Append(string.Format(td1, rule.levelname));
                    builder.Append("</tr>");
                }
            }
        }
        if (SelectNum == 0)
        {
            RaiseErrorMessage("请勾选会员信息");
            return;
        }
        this.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
        this.Response.ContentType = "text/xls";
        this.Response.AddHeader("Content-Disposition", string.Format("inline; filename=" + HttpUtility.UrlEncode(Encoding.UTF8.GetBytes("会员信息")) + "({0:yyyy-MM-dd}).xls", DateTime.Now));
        this.Response.Charset = "utf-8";
        this.Response.Write(builder.ToString());
        this.Response.End();
    }
    #endregion