datatable excel
时间: 2023-12-07 13:39:50 浏览: 92
以下是使用C#中的DataTable导出Excel的方法:
```csharp
//引用命名空间
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//定义导出Excel的方法
public static void ExportToExcel(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 = "";
int i = 0;
//定义表头
foreach (DataColumn dc in dt.Columns)
{
i++;
colHeaders += dc.ColumnName + "\t";
if (i < dt.Columns.Count)
{
colHeaders += "\t";
}
}
HttpContext.Current.Response.Write(colHeaders + "\n");
//定义单元格内容
foreach (DataRow dr in dt.Rows)
{
i = 0;
foreach (DataColumn dc in dt.Columns)
{
i++;
ls_item += dr[dc.ColumnName].ToString() + "\t";
if (i < dt.Columns.Count)
{
ls_item += "\t";
}
}
HttpContext.Current.Response.Write(ls_item + "\n");
ls_item = "";
}
HttpContext.Current.Response.End();
}
```
调用该方法,传入DataTable和文件名即可导出Excel文件:
```csharp
DataTable dt = new DataTable();
//填充DataTable
//...
ExportToExcel(dt, "example.xlsx");
```
阅读全文