asp.net 将数据导出到excel的完整代码?整了很长时间没能出来,谢谢

发布网友 发布时间:2024-10-24 01:12

我来回答

1个回答

热心网友 时间:2024-11-06 05:03

我这里有把dataTable的转为excel的数据。你把datalist 转为datatable就行了。是CSV文件,兼容EXCEL2003和2007.后面还有导出纯xls文件的,导出为2003版,但在模态窗口中不能用。。。
CSV:
/// <param name="dt">dataTable</param>
/// <param name="fileName">文件名称</param>
public static void ExportCSV(DataTable dt, string fileName)
{
HttpContext.Current.Response.Clear();

System.IO.StringWriter sw = new System.IO.StringWriter();

int iColCount = dt.Columns.Count;

for (int i = 0; i < iColCount; i++)
{
sw.Write("\"" + dt.Columns[i] + "\"");

if (i < iColCount - 1)
{
sw.Write(",");
}
}

sw.Write(sw.NewLine);

foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
sw.Write("\"" + dr[i].ToString() + "\"");
else
sw.Write("\"\"");
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}

sw.Close();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(fileName) + "\"");

HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

HttpContext.Current.Response.Write(sw);

HttpContext.Current.Response.End();
}

下面是导出xls,
/// <summary>
/// 普通导出EXECL的方法
/// </summary>
/// <param name="dt">数据表</param>
/// <param name="fileName">文件名</param>
/// <param name="page">固定输入:page</param>
public void CreateExcel(DataTable dt,string fileName,Page page)
{
HttpResponse resp;
resp = page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" +HttpContext.Current.Server.UrlPathEncode(fileName));
string colHeaders = "", ls_item = "";

////定义表对象与行对象,同时用DataSet对其值进行初始化
//DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;

//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
colHeaders += dt.Columns[i].Caption.ToString() + "\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}

}
resp.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息

//逐行处理数据
foreach (DataRow row in myRow)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
ls_item += row[i].ToString().Trim().Replace("\r\n", " ") + "\n";
}
else
{
ls_item += row[i].ToString().Trim().Replace("\r\n", " ") + "\t";
}

}
resp.Write(ls_item);
ls_item = "";

}
resp.End();
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com