导出excel的asp.net代码
时间: 2023-02-20 14:59:19 浏览: 108
要在 ASP.NET 中导出 Excel,您可以使用如下代码:
```
using System;
using System.Data;
using System.IO;
using System.Web.UI;
using Microsoft.Office.Interop.Excel;
namespace ExportExcel
{
public partial class Export : Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
Application excel = new Application();
Workbook workbook = excel.Workbooks.Add(Type.Missing);
Worksheet sheet = workbook.ActiveSheet;
sheet.Name = "ExportedFromDatatable";
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
sheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sheet.Cells[i + 2, j + 1] = dt.Rows[i][j];
}
}
workbook.SaveAs(Response.OutputStream);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExportedFile.xlsx");
Response.Flush();
Response.End();
}
}
}
```
请注意,上面的代码使用了 Microsoft.Office.Interop.Excel 库,因此您需要先安装该库。
这段代码会创建一个包含三列的 DataTable,分别为 Id、Name 和 Country,然后通过 Microsoft.Office.Interop.Excel 库创建 Excel 工作簿并将数据写入该工作簿。最后,通过 HTTP 响应将工作簿以 .xlsx 格式导出到客户端。
阅读全文