從數據庫讀取數據,導出成Excel文檔
void btnExport_Click(object sender, EventArgs e) { IList<string> fields = new List<string>(); IList<string> headers = new List<string>(); fields.Add("數據庫字段名1"); headers.Add("Excel字段名1"); fields.Add("數據庫字段名2"); headers.Add("Excel字段名2"); StringBuilder strFlag = new StringBuilder(); foreach (string head in headers) { strFlag.Append(head + ","); if (head == headers[headers.Count - 1]) { strFlag = strFlag.Remove(strFlag.Length - 1, 1); strFlag.Append("\r\n"); } } DataSet dt = new DataSet();//從數據庫獲取到數據 if (dt != null && dt.Tables[0].Rows.Count > 0) { foreach (DataRow row in dt.Tables[0].Rows) { foreach (string field in fields) { strFlag.Append(row[field]).Append(","); if (field == fields[headers.Count - 1]) { strFlag = strFlag.Remove(strFlag.Length - 1, 1); strFlag.Append("\r\n"); } } } Page.Response.Clear(); Page.Response.Buffer = false; Page.Response.Charset = "GB2312"; Page.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel文件名.csv"); Page.Response.ContentType = "application/octet-stream"; Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Page.EnableViewState = false; Page.Response.Write(strFlag.ToString()); Page.Response.End(); } }