如何在 c# ASP.NET Web Forms 中将搜索结果从 Gridview 导出到 Excel

How to export search results from Gridview to Excel in c# ASP.NET Web Forms

我只想将搜索结果导出到 excel 电子表格,但无论出于何种原因,我正在导出所有数据库 table。请帮忙!

这是我的代码:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

namespace Inventory.pages
{
    public partial class view : System.Web.UI.Page
    {

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Equipment"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {            
                SqlCommand cmd = new SqlCommand("SELECT * FROM Equipment ORDER by BLDG", conn);
                SqlDataAdapter DA = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                DA.Fill(ds);
                View_Results.DataSource = ds;
                View_Results.DataBind();
                conn.Close();
        }

        public void search()
        {
            string sqlQuery = "SELECT *" +
                              "FROM Equipment WHERE " +
                              "[Description] LIKE @SEARCH OR [Manufacturer] LIKE @SEARCH OR [MODEL_NO] LIKE @SEARCH " +
                              "OR [SERIAL_NO] LIKE @SEARCH OR [GROUP] LIKE @SEARCH " +
                              "OR [BLDG] LIKE @SEARCH OR [Room] LIKE @SEARCH OR [FIRST] LIKE @SEARCH " +
                              "OR [LAST] LIKE @SEARCH OR [INSTALLED] LIKE @SEARCH " +
                              "OR [GROUP] LIKE @SEARCH";

            SqlCommand cmd = new SqlCommand(sqlQuery, conn);
            cmd.Parameters.Add(new SqlParameter("@SEARCH", "%" + SearchBox.Text + "%"));
            SqlDataAdapter DA = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            DA.Fill(ds);
            View_Results.DataSource = ds;
            View_Results.DataBind();
            conn.Close(); 
        }
        protected void Search_Click(object sender, EventArgs e)
        {
            search();
        }

        protected void Download_Results_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=EquipmentQuery.xls");
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            View_Results.RenderControl(hw);
            Response.Write(sw.ToString());
            Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

      }
}

    <%@ Page Title="" Language="C#" MasterPageFile="~/pages/withoutsidebar.Master" AutoEventWireup="true" CodeBehind="view.aspx.cs" Inherits="Inventory.pages.view" %>

    <asp:Content ID="Content" ContentPlaceHolderID="Content" runat="server">
            <asp:TextBox ID="SearchBox" runat="server" CssClass="ViewSearch" Font-Italic="True" Font-Names="Arial" Font-Size="11px" ForeColor="#333333" Height="19px" TextMode="Search" Width="220px">Search here...</asp:TextBox>
            <asp:Button ID="Search" runat="server" Height="25px" OnClick="Search_Click" Text="Search" Width="100px"  Font-Size="11px" />
            <asp:Button ID="Download_Results" runat="server" Font-Size="11px" Height="25px" OnClick="Download_Results_Click" Text="Download Results" />
            <br />
            <br />
            <asp:GridView CssClass="View_Grid" ID="View_Results" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" CellPadding="2" RowStyle-Width="20px" AlternatingRowStyle-BackColor="#99ccff">
                <Columns>
                    <asp:BoundField HeaderText="PROPERTY NUMBER" DataField="PROP_NO" ControlStyle-CssClass="PROP_NO" >
                    <ControlStyle BorderWidth="1px" Height="10px" Width="35px" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="MANUFACTURER" DataField="Manufacturer" ControlStyle-CssClass="MANUFACTURER" >
                    <ControlStyle BorderWidth="1px" Height="20px" Width="35px" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="DESCRIPTION" DataField="DESCRIPTION" ControlStyle-CssClass="DESCRIPTION" >
                    <ControlStyle BorderWidth="1px" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="MODEL NUMBER" DataField="MODEL_NO" ControlStyle-CssClass="MODEL_NUMBER" >
                    <ControlStyle BorderWidth="1px" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="SERIAL NUMBER" DataField="SERIAL_NO" ControlStyle-CssClass="SERIAL_NUMBER">
                    <ControlStyle BorderWidth="1px" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="GROUP" DataField="GROUP" ControlStyle-CssClass="GROUP" >
                    <ControlStyle BorderWidth="1px" />
                    </asp:BoundField>
                   <asp:TemplateField HeaderText="LOCATION" ControlStyle-CssClass="LOCATION">
                    <ItemTemplate>
                         <asp:Label ID="Location" runat="server" Text='<%#Eval("BLDG")+ "-" + Eval("ROOM")%>' ></asp:Label>
                    </ItemTemplate>

    <ControlStyle CssClass="LOCATION"></ControlStyle>
                    </asp:TemplateField>
                    <asp:BoundField HeaderText="DATE INSTALLED" DataField="INSTALLED" ControlStyle-CssClass="INSTALLED">
                    <ControlStyle BorderWidth="1px" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="ACCOUNT" DataField="ACCOUNT" ControlStyle-CssClass="ACCOUNT">
                    <ControlStyle BorderWidth="1px" />
                    </asp:BoundField>
                    <asp:TemplateField HeaderText="OWNER" ControlStyle-CssClass="OWNER">
                    <ItemTemplate>
                         <asp:Label ID="Owner" runat="server" Text='<%#Eval("LAST")+ "," + Eval("FIRST")%>' ></asp:Label>
                    </ItemTemplate>

    <ControlStyle CssClass="OWNER"></ControlStyle>
                    </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
                <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
                <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
                <RowStyle BackColor="White" ForeColor="#003399" />
                <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
                <SortedAscendingCellStyle BackColor="#EDF6F6" />
                <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
                <SortedDescendingCellStyle BackColor="#D6DFDF" />
                <SortedDescendingHeaderStyle BackColor="#002876" />
            </asp:GridView>
    </asp:Content>

任何帮助将不胜感激,谢谢 -- 新手程序员

每当您在 Page_Load 事件中将数据绑定到数据控件时,请考虑使用 Page.IsPostBack

protected void Page_Load(object sender, EventArgs e)
{                        
  if(!Page.IsPostBack)
  {
            SqlCommand cmd = new SqlCommand("SELECT * FROM Equipment ORDER by BLDG", conn);
            SqlDataAdapter DA = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            DA.Fill(ds);
            View_Results.DataSource = ds;
            View_Results.DataBind();
            conn.Close();
  }
}

这是因为,当您点击一个按钮时,您的页面仍会刷新,这意味着 Page_Load 事件将再次触发,您将再次将相同的数据绑定到 gridview,覆盖 已搜索 结果集。您可以检查页面是通过单击按钮加载(Page.IsPostBack)还是第一次加载页面(!Page.IsPostBack),并相应地进行数据绑定。