首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 匯出 Excel 替代方案:後台資料繫結與 HTTP 下載(四)

     編輯:關於C語言

利用 ASP.NET Repeater 繫結資料,配合 HTTP 標頭將頁面輸出為 Excel 檔案下載,避免使用 COM 互操作導致的 Excel 進程殘留問題。

後台程式碼

protected void Page_Load(object sender, EventArgs e) {
    this.EnableViewState = false;
    LoadData();

    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "GB2312";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("學生成績表.xls", Encoding.UTF8));
    Response.ContentEncoding = Encoding.GetEncoding("GB2312");
    Response.ContentType = "application/ms-excel";
}

private void LoadData() {
    var users = new List<User> {
        new User(1, "劉一", 81), new User(2, "陳二", 82), new User(3, "張三", 83),
        new User(4, "李四", 84), new User(5, "王五", 85), new User(6, "趙六", 86),
        new User(7, "孫七", 87), new User(8, "周八", 88), new User(9, "吳九", 89),
        new User(10, "鄭十", 80)
    };
    rptData.DataSource = users;
    rptData.DataBind();
}

[Serializable]
private class User {
    public int id { get; set; }
    public string name { get; set; }
    public decimal achievement { get; set; }
    public User() {}
    public User(int id, string name, decimal achievement) {
        this.id = id; this.name = name; this.achievement = achievement;
    }
}

前端 Repeater 輸出 HTML 表格,瀏覽器接收 application/ms-excel 內容類型自動啟動 Excel 開啟或下載。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved