这段时间用到了导出Excel的功能,这个功能还是比较常用的,我常用的有两个方法,现在整理一下,方便以后查看。
一、实现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 + " "; //栏位:自动跳到下一单元格 } title = title.Substring(0, title.Length - 1) + " "; 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() + " "; //内容:自动跳到下一单元格 } line = line.Substring(0, line.Length - 1) + " "; sw.Write(line); } sw.Close(); fs.Close(); }
二、实现DataTable数据导出到本地,路径可以由用户自主选择。
/// <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 + " "; //栏位:自动跳到下一单元格 } ls_item = ls_item.Substring(0, ls_item.Length - 1) + " "; foreach (DataRow row in myRow) { for (i = 0; i < cl; i++) { if (i == (cl - 1)) { ls_item += row[i].ToString() + " "; } else { ls_item += row[i].ToString() + " "; } } Response.Output.Write(ls_item); ls_item = string.Empty; } Response.Output.Flush(); Response.End(); }
三、方法的调用。
第一种方法的调用:
this.dataTableToCsv(dt, @"C:UsersAdminDesktop收听率" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls"); //调用函数
第二种方法的调用:
CreateExcel(dt, "application/ms-excel", "Excel" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls");//调用函数
这两种方法都是可以直接调用的,只需要传入需要的参数即可。
如果是通过前台js方式实现,跳转href为实现数据导出的页面地址,我是通过前台跳转到ashx页面实现的
ashx页面内容
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部分内容
$("#Excel").bind('click', function () { var url = "AjaxHandler/RadioFamilyDayNumber.ashx?Action=Excel"; window.location.href = url;//导出Excel })