利用 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 開啟或下載。