将“导出到Excel”按钮添加到网页,以将gridview导出到web应用程序中的Excel

时间:2010-12-09 11:22:30

标签: asp.net vb.net web-applications export-to-excel

我为一家诊所建立了一个患者管理软件,我需要从ASP.net网格视图导出patiet列表到excel文件

我的问题是:

有没有办法将gridview导出为ex​​cel 我正在使用vb.net和visual web developer 2010

我将数据源从高级搜索页面存储到会话中并重定向到结果页面 这是结果页面的代码

Partial Class Sresults
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    GridView1.DataSource = Session("dsource")
    GridView1.DataBind()

End Sub

Protected Sub Backbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Backbtn.Click
    Session("dsource") = ""
    Response.Redirect("searchme.aspx")

End Sub

Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
    Response.Write(GridView1.Rows.Count.ToString + " Records")
End Sub
End Class

2 个答案:

答案 0 :(得分:3)

点击按钮

下面的代码
// Get DataTable that DataGrid is bound to.
var dataTable = (DataTable)dataGrid.DataSource;

// Create new ExcelFile.
var ef = new ExcelFile();
// Add new worksheet to the file.
var ws = ef.Worksheets.Add(dataTable.TableName);
// Insert the data from DataTable to the worksheet starting at cell "A1".
ws.InsertDataTable(dataTable, "A1", true);

// Stream file to browser.
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=Employee.xls");
ef.SaveXls(Response.OutputStream);
Response.End();

答案 1 :(得分:0)

首先,您必须将以下内容添加到page指令以避免运行时错误

 EnableEventValidation ="false"

将gridview添加到aspx页面 会话“dsource”从包含连接字符串和select命令的高级搜索页面传递数据源 那么这里是代码


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Threading;
using System.IO;
using System.Reflection;

public partial class csresults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

    gridview1.DataSource = Session["dsource"];
    gridview1.DataBind();




}


  public override void VerifyRenderingInServerForm(Control control)
{

}



protected void Button2_Click(object sender, EventArgs e)
{
    HtmlForm form = new HtmlForm();
    string attachment = "attachment; filename=Patients.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/ms-excel";
    StringWriter stw = new StringWriter();
    HtmlTextWriter htextw = new HtmlTextWriter(stw);
    form.Controls.Add(gridview1);
    this.Controls.Add(form);
    form.RenderControl(htextw);
    Response.Write(stw.ToString());
    Response.End();
}

}