C# Excel的導出 經典案例

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
發佈了54 篇原創文章 · 獲贊 6 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章