انتخاب ستون های انتخاب شده به صفحه اکسل با استفاده از GridView در ASP.Net
در مقاله قبلی استفاده از GridView در خروج سوابق انتخاب شده به صفحه اکسل در ASP.Net را توضیح دادیم که چگونه برای خروج ردیف های انتخاب شده ازکنترل ASP.Net GridView به ExcelSheetرا نشان دادیم . در این مقاله توضیح خواهیم داد که چگونه تنها ستون های انتخاب شده GridView را به صفحه اکسل منتقل کنید. می توانید انتخاب کاربر را انتخاب کنید یا علامت چک های مربوط به ستون را انتخاب کنید، در نتیجه ستون ها و یا زمینه های که می خواهیم به جدول اکسل منتقل می شود .
بانک اطلاعاتی
از پایگاه داده نمونه Northwind مایکروسافت برای این مقاله استفاده می کنیم.
کد GridView HTML
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol0" runat="server" Checked = "true" />
<asp:Label ID="lblCol0" runat="server" Text = "CustomerID"/>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCustomerID" runat="server"
Text='<%# Eval("CustomerID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol1" runat="server" Checked = "true"/>
<asp:Label ID="lblCol1" runat="server" Text = "ContactName" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblContactName" runat="server"
Text='<%# Eval("ContactName")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkCol2" runat="server" Checked = "true" />
<asp:Label ID="lblCol2" runat="server" Text = "City"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%# Eval("City")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
همانطور که می بینید یک جعبه در HeaderTemplate برای هر ستون در GridView قرار داده ایم. این گزینه ها برای انتخاب یا حذف ستونها مورد استفاده قرار می گیرند
داده های مرتبط
ازتابع زیر برای اتصال داده ها از پایگاه داده SQL Server به کنترل GridView ASP.Net استفاده می شود
C #
private void BindGrid()
{
string strQuery = "select CustomerID,City,ContactName" +
" from customers";
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(strQuery);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
VB.Net
Private Sub BindGrid()
Dim strQuery As String = "select CustomerID,City,ContactName" & _
" from customers"
Dim dt As New DataTable()
Dim strConnString As [String] = System.Configuration.ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter()
Dim cmd As New SqlCommand(strQuery)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Sub
همانطور که می بینید در بالای تابع به سادگی SQL query را اجرا می کند و نتایج بازگشتی را به کنترل GridView ASP.Net متصل می کند. تابع فوق در صفحه رویداد بارگذاری صفحه وب ASP.Net فراخوانی می شود
C #
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
GetCheckBoxStates();
BindGrid();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If IsPostBack Then
GetCheckBoxStates()
End If
BindGrid()
End Sub
متوجه خواهید شد که یکی از تابع GetCheckBoxStates را در رویداد Page Load در صفحه می خواهیم . کار این تابع این است کهGridView checkboxes را در ViewState نگه می دارد . این تابع در زیر شرح داده شده است
C #
private void GetCheckBoxStates()
{
CheckBox chkCol0 = (CheckBox)GridView1.HeaderRow.Cells[0]
.FindControl("chkCol0");
CheckBox chkCol1 = (CheckBox)GridView1.HeaderRow.Cells[0]
.FindControl("chkCol1");
CheckBox chkCol2 = (CheckBox)GridView1.HeaderRow.Cells[0]
.FindControl("chkCol2");
ArrayList arr;
if (ViewState["States"] == null)
{
arr = new ArrayList();
}
else
{
arr = (ArrayList)ViewState["States"];
}
arr.Add(chkCol0.Checked);
arr.Add(chkCol1.Checked);
arr.Add(chkCol2.Checked);
ViewState["States"] = arr;
}
VB.Net
Private Sub GetCheckBoxStates()
Dim chkCol0 As CheckBox = DirectCast(GridView1.HeaderRow.Cells(0) _
.FindControl("chkCol0"), CheckBox)
Dim chkCol1 As CheckBox = DirectCast(GridView1.HeaderRow.Cells(0) _
.FindControl("chkCol1"), CheckBox)
Dim chkCol2 As CheckBox = DirectCast(GridView1.HeaderRow.Cells(0) _
.FindControl("chkCol2"), CheckBox)
Dim arr As ArrayList
If ViewState("States") Is Nothing Then
arr = New ArrayList()
Else
arr = DirectCast(ViewState("States"), ArrayList)
End If
arr.Add(chkCol0.Checked)
arr.Add(chkCol1.Checked)
arr.Add(chkCol2.Checked)
ViewState("States") = arr
End Sub
خروج ستون های انتخاب شده به صفحه اکسل با GridView
C #
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
ArrayList arr = (ArrayList)ViewState["States"];
GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
VB.Net
Protected Sub btnExportExcel_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GridView1.AllowPaging = False
GridView1.DataBind()
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF")
GridView1.HeaderRow.Cells(0).Style.Add("background-color", "green")
GridView1.HeaderRow.Cells(1).Style.Add("background-color", "green")
GridView1.HeaderRow.Cells(2).Style.Add("background-color", "green")
Dim arr As ArrayList = DirectCast(ViewState("States"), ArrayList)
GridView1.HeaderRow.Cells(0).Visible = Convert.ToBoolean(arr(0))
GridView1.HeaderRow.Cells(1).Visible = Convert.ToBoolean(arr(1))
GridView1.HeaderRow.Cells(2).Visible = Convert.ToBoolean(arr(2))
GridView1.HeaderRow.Cells(0).FindControl("chkCol0").Visible = False
GridView1.HeaderRow.Cells(1).FindControl("chkCol1").Visible = False
GridView1.HeaderRow.Cells(2).FindControl("chkCol2").Visible = False
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim row As GridViewRow = GridView1.Rows(i)
row.Cells(0).Visible = Convert.ToBoolean(arr(0))
row.Cells(1).Visible = Convert.ToBoolean(arr(1))
row.Cells(2).Visible = Convert.ToBoolean(arr(2))
row.BackColor = System.Drawing.Color.White
row.Attributes.Add("class", "textmode")
If i Mod 2 <> 0 Then
row.Cells(0).Style.Add("background-color", "#C2D69B")
row.Cells(1).Style.Add("background-color", "#C2D69B")
row.Cells(2).Style.Add("background-color", "#C2D69B")
End If
Next
GridView1.RenderControl(hw)
Dim style As String = "<style> .textmode { mso-number-format:\@; } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.[End]()
End Sub
همانطور که در بالا ذکر شده همه چیز همانند استفاده GridView در خروج اکسل است، تنها تفاوت مخفی کردن GridView cells بر اساس بررسی مقادیر مربوطه به ردیف سرصفحه می باشد. به عبارت دیگر پنهان کردن ستون ها است . نگاهی به تصاویر زیر بیندازید :
فعال یا غیر فعال کردن ستون ها با استفاده از ASP.Net GridView
.png)
خروج صفحه اکسل با ستون های انتخاب شده
.png)