语言:ASP.net
平台:带有ASP.net的Visual Studio 2008
技术:用于ASP.net
介绍
1.将gridview添加到aspx文件中
2.在aspx文件中添加一个按钮,并将名称命名为“ btnExportToExcel”
3.在aspx.cs文件中编写代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace ExampleOnAjax
{
public partial class ExportFiles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtRecords = new DataTable();
dtRecords.Columns.Add("State", typeof(string));
dtRecords.Columns.Add("City", typeof(string));
DataRow dr = dtRecords.NewRow();
dr["State"] = "Karnataka";
dr["City"] = "Bangalore";
dtRecords.Rows.Add(dr);
grdData.DataSource = dtRecords;
grdData.DataBind();
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/ms-excel";
Response.Charset ="";
Page.EnableViewState = false;
Response.AddHeader("Content-Disposition", "inline;filename=report.xls");
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
grdData.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}
}
摘要:
运行应用程序,单击按钮,它将要求保存或打开文件,如果保存,它将保存到磁盘中
或者,如果单击“打开”,则直接打开excel文件。
From: https://bytes.com/topic/net/insights/912685-how-export-gridview-data-excel