简体   繁体   English

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

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

I want to export ONLY the search results to an excel spreadsheet, but for whatever reason I am missing, I am exporting all of the database table instead. 我只想将搜索结果导出到excel电子表格,但是由于我缺少的任何原因,我导出了所有数据库表。 Please help! 请帮忙!

Here is my code: 这是我的代码:

    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>

Any help would be appreciated, thank you -- Novice Programmer 任何帮助将不胜感激,谢谢您-新手程序员

Whenever you bind a data to a data control in Page_Load event, please consider using Page.IsPostBack 每当在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();
  }
}

This is because, when you click a button, your page will be still refreshed, which means the Page_Load event will be fired again, and you will bind the same data to gridview again, overwriting the Searched result set . 这是因为,当您单击按钮时,页面仍将刷新,这意味着将再次触发Page_Load事件,并且您将相同的数据再次绑定到gridview,从而覆盖了Searched 结果集 You can check whether the page is loaded by a button click ( Page.IsPostBack ) or the page is loaded the first time ( !Page.IsPostBack ), and do your data binding accordingly. 您可以检查是通过单击按钮( Page.IsPostBack )加载页面还是第一次加载页面( !Page.IsPostBack ),并进行相应的数据绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM