C# 通过文件流的方式将datatable导出至excel返回
时间: 2023-09-06 19:13:10 浏览: 230
C#实现将DataTable内容输出到Excel表格的方法
好的,以下是示例代码:
```csharp
using System.IO;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
public static void ExportDataTableToExcel(DataTable dt, string fileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());
HttpContext.Current.Response.ContentType = "application/ms-excel";
string colHeaders = "", ls_item = "";
//定义表对象与行对象,同时用DataSet对其值进行初始化
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;
//向HTTP输出流中写入列头数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))
{
colHeaders += dt.Columns[i].Caption.ToString();
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
HttpContext.Current.Response.Write(colHeaders + "\n");
//逐行处理数据
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() + "\t";
}
}
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
HttpContext.Current.Response.Write(ls_item + "\n");
ls_item = "";
}
HttpContext.Current.Response.End();
}
```
使用方法:
```csharp
// 假设 DataTable 名为 dt,文件名为 example.xlsx
ExportDataTableToExcel(dt, "example.xlsx");
```
这个方法会将 DataTable 中的数据导出为 .xlsx 文件,并返回给客户端下载。
阅读全文