C# asp.net 实现导出Excel

时间:2023-03-09 13:36:59
C# asp.net 实现导出Excel

原文地址:传送门

这段时间用到了导出Excel的功能,这个功能还是比较常用的,我常用的有两个方法,现在整理一下,方便以后查看。

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 = ; i < table.Columns.Count; i++)
{
title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格
}
title = title.Substring(, title.Length - ) + "\n";
sw.Write(title);
foreach (DataRow row in table.Rows)
{
string line = "";
for (int i = ; i < table.Columns.Count; i++)
{
line += row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格
}
line = line.Substring(, line.Length - ) + "\n";
sw.Write(line);
}
sw.Close();
fs.Close();
}

2.实现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 = ;
int cl = dt.Columns.Count;
for (int j = ; j < dt.Columns.Count; j++)
{
ls_item += dt.Columns[j].ColumnName + "\t"; //栏位:自动跳到下一单元格
}
ls_item = ls_item.Substring(, ls_item.Length - ) + "\n";
foreach (DataRow row in myRow)
{
for (i = ; i < cl; i++)
{
if (i == (cl - ))
{
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.实现DataTable数据导出到本地,路径可以由用户自主选择,同时支持自定义Excel的样式,较为灵活。

/// <summary>
/// 以流的形式,可以设置很丰富复杂的样式
/// </summary>
/// <param name="content">Excel中内容(Table格式)</param>
/// <param name="filename">文件名</param>
/// <param name="cssText">样式内容</param>
public void ExportToExcel(string filename, string content, string cssText)
{
var res = HttpContext.Current.Response;
content = string.Format("<style type='text/css'>{0}</style>{1}", cssText, content); res.Clear();
res.Buffer = true;
res.Charset = "UTF-8";
res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
res.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
res.ContentType = "application/ms-excel;charset=UTF-8";
res.Write(content);
res.Flush();
res.End();
}

方法的调用

第一种方法的调用:

this.dataTableToCsv(dt, @"C:\Users\Admin\Desktop\收听率" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls"); //调用函数

第二种方法的调用:

CreateExcel(dt, "application/ms-excel", "Excel" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls");//调用函数

第三种方法的调用:

// 数据源,html格式table
string content = "<table><tr><td class='ftd'>字段1</td></tr></table>";
// 自定义class样式
string css = ".ftd{width:200px;}"; // 调用
this.ExportToExcel("demo.xls", content, css);

这三种方法都是可以直接调用的,只需要传入需要的参数即可。

如果是通过前台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
})