這段時間用到了導出Excel的功能,這個功能仍是比較經常使用的,我經常使用的有兩個方法,如今整理一下,方便之後查看。app
1、實現DataTable數據導出到本地,須要本身傳進去導出的路徑。函數
/// <summary> /// DataTable導出到Excel /// </summary> /// <param name="table">DataTable類型的數據源</param> /// <param name="file">須要導出的文件路徑</param> public void dataTableToCsv(DataTable table, string file) { string title = ""; FileStream fs = new FileStream(file, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default); for (int i = 0; i < table.Columns.Count; i++) { title += table.Columns[i].ColumnName + "\t"; //欄位:自動跳到下一單元格 } title = title.Substring(0, title.Length - 1) + "\n"; sw.Write(title); foreach (DataRow row in table.Rows) { string line = ""; for (int i = 0; i < table.Columns.Count; i++) { line += row[i].ToString().Trim() + "\t"; //內容:自動跳到下一單元格 } line = line.Substring(0, line.Length - 1) + "\n"; sw.Write(line); } sw.Close(); fs.Close(); }
2、實現DataTable數據導出到本地,路徑能夠由用戶自主選擇。this
/// <summary> /// DataTable導出到Excel /// </summary> /// <param name="dt">DataTable類型的數據源</param> /// <param name="FileType">文件類型</param> /// <param name="FileName">文件名</param> public void CreateExcel(DataTable dt, string FileType, string FileName) { Response.Clear(); Response.Charset = "UTF-8"; Response.Buffer = true; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\""); Response.ContentType = FileType; string colHeaders = string.Empty; string ls_item = string.Empty; DataRow[] myRow = dt.Select(); int i = 0; int cl = dt.Columns.Count; for (int j = 0; j < dt.Columns.Count; j++) { ls_item += dt.Columns[j].ColumnName + "\t"; //欄位:自動跳到下一單元格 } ls_item = ls_item.Substring(0, ls_item.Length - 1) + "\n"; foreach (DataRow row in myRow) { for (i = 0; i < cl; i++) { if (i == (cl - 1)) { ls_item += row[i].ToString() + "\n"; } else { ls_item += row[i].ToString() + "\t"; } } Response.Output.Write(ls_item); ls_item = string.Empty; } Response.Output.Flush(); Response.End(); }
3、方法的調用。url
第一種方法的調用:spa
this.dataTableToCsv(dt, @"C:\Users\Admin\Desktop\收聽率" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls"); //調用函數
第二種方法的調用:excel
CreateExcel(dt, "application/ms-excel", "Excel" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls");//調用函數
這兩種方法都是能夠直接調用的,只須要傳入須要的參數便可。code
若是是經過前臺js方式實現,跳轉href爲實現數據導出的頁面地址,我是經過前臺跳轉到ashx頁面實現的 blog
ashx頁面內容string
public void ProcessRequest(HttpContext context) {string message = ""; string Action = context.Request["Action"]; switch (Action) {case "Excel": DataTable Radio = GetExcleData(context); //獲取導出數據源 RadioCommon helper = new RadioCommon(); helper.ExportExcel(Radio, "application/ms-excel", "Excel" + DateTime.Now.ToString("yyyy-MM-dd HHmmss")); break; } context.Response.Write(message); }
js部份內容it
$("#Excel").bind('click', function () { var url = "AjaxHandler/RadioFamilyDayNumber.ashx?Action=Excel"; window.location.href = url;//導出Excel })