有人可以看看我的代码吗?此代码运行良好,但我想在数据导出到 Excel 时删除第一列和第二列。我尝试GridView1.Columns[0].Visible = false;
但它不起作用。
这是我的 aspx
<%@ Page Title="VRQ" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="EmployeePage.aspx.cs" Inherits="EmployeePage"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
function Button1_onclick() {
//open new window set the height and width =0,set windows position at bottom
var a = window.open ('','','left =' + screen.width + ',top=' + screen.height + ',width=0,height=0,toolbar=0,scrollbars=0,status=0');
//write gridview data into newly open window
a.document.write(document.getElementById('innerdata').innerHTML);
a.document.close();
a.focus();
//call print
a.print();
a.close();
return false;
}
function OpenFile(KEYW) {
window.open("ResumePage.aspx?bid=" + KEYW, "ResumeContext");
}
</script>
<asp:Button ID="btnbacksearch" runat="server" Text="Back to Search"
Width="127px" OnClick="btnbacksearch_Click" CssClass="plainbutton" />
<asp:Button ID="btnExportToExcel" runat="server" OnClick="btnExportToExcel_Click"
Text="Export Results to Excel" Width="174px" CssClass ="plainbutton" />
<asp:Button
ID="btnGenerateSF" runat="server" OnClick="btnGenerateSF_Click"
Text="Generate Resume" Width="137px" CssClass ="plainbutton"
Visible="False" />
<asp:DropDownList ID="ddStatus" runat="server"
onselectedindexchanged="ddStatus_SelectedIndexChanged" AutoPostBack="True"
Visible="False" Width="150px">
<asp:ListItem Selected="True" Value="Active">Active Personnel</asp:ListItem>
<asp:ListItem Value="Inactive">Inactive Personnel</asp:ListItem>
</asp:DropDownList>
<div style="font-size: 11pt; font-family: Tahoma; text-align:center "><strong>
SEARCH SUMMARY</strong></div>
<div style="font-size: 10pt; font-family: Tahoma; text-align:center ">
<asp:Label ID="LabelCaption" runat="server" Text="Label"></asp:Label>
</div>
<div id = "innerdata" style="size: landscape;" >
<asp:GridView ID="GridView1" runat="server"
CellPadding="4" DataSourceID="SqlDataSource1"
onrowcreated="GridView1_RowCreated"
AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"
DataKeyNames="IDNo" AllowSorting="True" Width="100%"
PageSize="30" EmptyDataText="No Existing Records." CssClass="GridView"
onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False"
onsorted="GridView1_Sorted" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkSelect" Text="View" CommandName ="Select" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkPrintRep1" Text="Project Selection" CommandName ="PrintSF330" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="70px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="fullname" HeaderText="Name" ReadOnly="True"
SortExpression="fullname" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="YearsExperience" HeaderText="Experience"
SortExpression="YearsExperience" >
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Job" HeaderText="Position" SortExpression="Job" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Search Results" SortExpression ="SearchDetails">
<ItemTemplate>
<%# HighlightText(Convert.ToString(Eval("SearchDetails"))) %> </ItemTemplate>
<ItemStyle Width="300px" />
</asp:TemplateField>
</Columns>
<RowStyle CssClass="GridRowStyle"/>
<PagerStyle HorizontalAlign="Center" />
<SelectedRowStyle CssClass="GridSelected" />
<HeaderStyle CssClass="GridHeader" Height="10px" />
<PagerStyle CssClass="GridFooterStyle"/>
</asp:GridView></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:HRIS_ConnectionString %>"
ProviderName="<%$ ConnectionStrings:HRIS_ConnectionString.ProviderName %>"
SelectCommand="select i.IDNo,concat(lastname,', ',firstname,' ',middlename) as fullname,e.tYrsExperience as YearsExperience,p.Description as Job,'' as SearchDetails FROM employeesinfo i inner join ecd e on e.empid=i.idno
left outer join Position p on p.idno = e.presentjob">
</asp:SqlDataSource>
<vt:MessageBox ID="MessageBox1" runat="server"></vt:MessageBox>
</asp:Content>
这是我的 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.Text.RegularExpressions;
using System.IO;
using System.Text;
public partial class EmployeePage : System.Web.UI.Page
{
string sqry = ""; string scolumn = "";
string origQry = String.Empty;
public string keyword = "";
public string curAlpha = "";
public int iCtr = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["QRY_CONDITIONS"] == null) Response.Redirect("Default.aspx");
scolumn = Session["QRY_DETAIL"].ToString();
sqry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user == null) return;
if (user.IsSuperAdmin && sqry == "ALL")
{
ddStatus.Visible = true;
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") ;
}
else if(sqry == "ALL")
{
ddStatus.Visible = false;
sqry = " where ifnull(i.activestatus,0) = 1 ";
}
origQry = sqry;
if (Request.QueryString["keyword"] != null) keyword = Request.QueryString["keyword"].ToString().TrimEnd().TrimStart();
if (!IsPostBack)
{
if (keyword == "")
{
sqry = sqry + " and i.lastname like 'A%' ";
Session["QRY_alpha"] = " and i.lastname like 'A%' ";
curAlpha = "A";
}
LoadStates();
BindData();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
curAlpha = (string)ViewState["curAlpha"];
}
protected override object SaveViewState()
{
ViewState["curAlpha"] = curAlpha;
return base.SaveViewState();
}
private void BindData()
{
modPublic myMod = new modPublic();
SqlDataSource1.SelectCommand = "SELECT distinct i.idno,concat(i.lastname,', ',i.firstname,' ',i.middlename) as fullname,e.tYrsExperience as YearsExperience,e.Position as Job," + scolumn + " as SearchDetails FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + sqry + " order by i.lastname,i.firstname";
SqlDataSource1.Select(new DataSourceSelectArguments());
object o = myMod.ExecuteScalar("select count(distinct i.idno) as ctr FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + origQry + " ");
LabelCaption.Text = o.ToString() + " Record(s) found";
if (keyword == "")
{
GridView1.AllowPaging = false;
GridView1.Columns[5].Visible = false;
}
else
{
GridView1.Columns[5].Visible = true;
}
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindData();
GridView1.PageIndex = e.NewPageIndex;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AlphaPaging")
{
curAlpha = e.CommandArgument.ToString();
sqry = sqry + " and i.lastname like '" + e.CommandArgument + "%'";
Session["QRY_alpha"] = " and i.lastname like '" + e.CommandArgument + "%'";
GridView1.AllowPaging = false;
BindData();
SaveStates();
//this.SqlDataSource1.SelectCommand = "Select * from [Table_1] WHERE theName LIKE '" + e.CommandArgument + "%'";
}
if (e.CommandName == "PrintSF330")
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=" + e.CommandArgument.ToString() + " ");
}
else if (e.CommandName == "Select")
{
SaveStates();
loadECD(e.CommandArgument.ToString());
}
}
//protected override object SaveViewState()
//{
// ViewState["alphacond"] = alphacond;
// return base.SaveViewState();
//}
//protected override void LoadViewState(object savedState)
//{
// if (Page.IsPostBack)
// {
// base.LoadViewState(savedState);
// alphacond = ViewState["alphacond"].ToString();
// }
//}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// e.Row.Attributes.Add("OnClick", "javascript:" + Page.GetPostBackClientEvent(GridView1, "Select$" + e.Row.RowIndex));
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
}
if (keyword == "")
{
if (e.Row.RowType == DataControlRowType.Footer)
{
GridViewRow grv = new GridViewRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal);
this.GridView1.Controls[0].Controls.Add(grv);
TableCell cell = new TableCell();
grv.Cells.Add(cell);
if (keyword == "")
cell.ColumnSpan = 5;
else
cell.ColumnSpan = 6;
for (int i = 65; i <= (65 + 25); i++)
{
string s = Char.ConvertFromUtf32(i);
if (s == curAlpha)
{
Label lt = new Label();
lt.Text = "[" + s + "]";
lt.Font.Bold = true;
lt.Font.Size = new FontUnit(12);
lt.Style["text-align"] = "middle";
cell.Controls.Add(lt);
}
else
{
LinkButton lb = new LinkButton();
lb.Text = s + " ";
lb.CommandArgument = s;
lb.CommandName = "AlphaPaging";
cell.Controls.Add(lb);
}
}
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
GridView1.Columns[0].Visible = false;
GridView1.AllowPaging = false;
BindData();
GridView1.DataBind();
GridViewExportUtil.Export("ReportResultsPage.xls", this.GridView1);
GridView1.AllowPaging = true;
BindData();
GridView1.Columns[0].Visible = false;
}
private void SaveStates()
{
if (Session["QRY_alpha"] == null) Session["QRY_alpha"] = "";
sqry = Session["QRY_CONDITIONS"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user.IsSuperAdmin && sqry == "ALL")
{
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") + Session["QRY_alpha"].ToString();
origQry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0");
}
else if (sqry == "ALL")
{
sqry = " where ifnull(i.activestatus,0) = 1 " + Session["QRY_alpha"].ToString();
origQry = " where ifnull(i.activestatus,0) = 1 ";
}
else
{
sqry = Session["QRY_CONDITIONS"].ToString() + Session["QRY_alpha"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
}
string tmp = "";
tmp = sqry + "|" +
scolumn + "|" +
keyword + "|" +
GridView1.SelectedIndex.ToString() + "|" +
GridView1.PageIndex.ToString() + "|" +
ddStatus.SelectedIndex.ToString() + "|" +
curAlpha + "|" +
origQry;
Session["PrevState"] = tmp;
}
public void LoadStates()
{
string tmp = (string)Session["PrevState"];
if (tmp == null)
{
return;
}
string[] arr = tmp.Split(new char[] { '|' });
sqry = arr[0];
scolumn = arr[1];
keyword = arr[2];
GridView1.SelectedIndex = Convert.ToInt32(arr[3]);
GridView1.PageIndex = Convert.ToInt32(arr[4]);
ddStatus.SelectedIndex = Convert.ToInt32(arr[5]);
curAlpha = arr[6];
origQry = arr[7];
}
void loadECD(string _idno)
{
SaveStates();
Response.Redirect("~/ECDMain.aspx?i=" + _idno);
}
protected void btnbacksearch_Click(object sender, EventArgs e)
{
Response.Redirect("~/Default.aspx");
}
protected void btnGenerateSF_Click(object sender, EventArgs e)
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=ALL&EmpIDs=" + GetEmpID());
}
private string GetEmpID()
{
string temp = ""; string empIDs = "";
foreach (GridViewRow gRow in GridView1.Rows)
{
temp = GridView1.DataKeys[gRow.RowIndex].Value.ToString();
empIDs = (empIDs == "" ? empIDs : empIDs + ",") + temp;
}
return "(" + empIDs + ")";
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && keyword !="")
e.Row.Cells[5].Text = e.Row.Cells[5].ToString().Replace(keyword,"<span style=//background-color: #FFFF00;//>" + keyword + "</span>");
}
public string HighlightText(string InputTxt)
{
// This function is called whenever text is displayed in the FirstName and LastName
// fields from our database. If we're not searching then just return the original
// input, this speeds things up a bit
if (string.IsNullOrEmpty(keyword))
{
return InputTxt;
}
else
{
// Otherwise create a new regular expression and evaluate the FirstName and
// LastName fields against our search string.
Regex ResultStr = default(Regex);
ResultStr = new Regex(keyword.Replace(" ", "|"), RegexOptions.IgnoreCase);
return ResultStr.Replace(InputTxt, new MatchEvaluator(ReplaceWords));
}
}
public string ReplaceWords(Match m)
{
// This match evaluator returns the found string and adds it a CSS class I defined
// as 'highlight'
return "<span class=highlight>" + m.ToString() + "</span>";
}
//protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
//{
// if ((e.Row.RowType == DataControlRowType.DataRow))
// {
// //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
// ((LinkButton)e.Row.FindControl("lnkResume")).Attributes.Add("onclick", "javascript:OpenFile('" + GridView1.DataKeys[e.Row.RowIndex].Value + "-" + keyword + "')");
// }
//}
protected void btnGenWord_Click(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
GridViewExportUtil.ExportWord("ReportResultsPage.doc", this.GridView1);
GridView1.AllowPaging = true;
}
protected void GridView1_Sorted(object sender, EventArgs e)
{
BindData();
}
protected void ddStatus_SelectedIndexChanged(object sender, EventArgs e)
{
sqry = sqry + " and i.lastname like '" + curAlpha + "%'";
BindData();
}
}
请有人可以帮助我。提前致谢