3.2 後台調取數據,導成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", System.Text.Encoding.UTF8));
Response.ContentEncoding = System.Text.Encoding.GetEncoding ("GB2312");
Response.ContentType = "application/ms-Excel";
//Response.End();
}
private void LoadData()
{
IList<User> users = new List<User>();
//測試數據
users.Add(new User(1, "劉一", 81));
users.Add(new User(2, "陳二", 82));
users.Add(new User(3, "張三", 83));
users.Add(new User(4, "李四", 84));
users.Add(new User(5, "王五", 85));
users.Add(new User(6, "趙六", 86));
users.Add(new User(7, "孫七", 87));
users.Add(new User(8, "周八", 88));
users.Add(new User(9, "吳九", 89));
users.Add(new User(10, "鄭十", 80));
rptData.DataSource = users;
rptData.DataBind();
}
[Serializable]
private class User
{
public User()
{
}
public User(int id, string name, decimal achIEvement)
{
this._id = id;
this._name = name;
this._achievement = achIEvement;
}
private int _id;
/// <summary>
/// 編號
/// </summary>
public int id
{
get { return _id; }
set { _id = value; }
}
private string _name;
/// <summary>
/// 姓名
/// </summary>
public string name
{
get { return _name; }
set { _name = value; }
}
private decimal _achIEvement;
/// <summary>
/// 成績
/// </summary>
public decimal achIEvement
{
get { return _achIEvement; }
set { _achIEvement = value; }
}
}
代碼說明:
Page_Load中依次加載數據,然後以ms-excel類型講web浏覽變成Excel文件下載。