Asp.Net GridView Seçili Satırları Excel veya Word’e Aktarma

Hazırlamış olduğunuz uygulamada öğrenci listelerini gridview ile listeledikten sonra Excel veya Word’e aktarma gereği duyabilirsiniz tıpkı benim gibi 🙂 aşağıdaki uygulama ile GridView içinden seçili olan satırları Excel veya Word’e aktarabilirsiniz.
İlk olarak aşağıdaki görüntü için form üzerine bir GridView ekliyoruz ve gösterilecek olan sütunları ayarlıyoruz.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Gridview Seçili Satırları Excel veya Worde Ektarma</title>
    <style type="text/css">
        .GridviewDiv
        {
            font-size: 100%;
            font-family: 'Lucida Grande' , 'Lucida Sans Unicode' , Verdana, Arial, Helevetica, sans-serif;
            color: #303933;
        }
        Table.Gridview
        {
            border: solid 1px #df5015;
        }
        .Gridview th
        {
            color: #FFFFFF;
            border-right-color: #abb079;
            border-bottom-color: #abb079;
            padding: 0.5em 0.5em 0.5em 0.5em;
            text-align: center;
        }
        .Gridview td
        {
            border-bottom-color: #f0f2da;
            border-right-color: #f0f2da;
            padding: 0.5em 0.5em 0.5em 0.5em;
        }
        .Gridview tr
        {
            color: Black;
            background-color: White;
            text-align: left;
        }
        :link, :visited
        {
            color: #DF4F13;
            text-decoration: none;
        }
        .highlight
        {
            text-decoration: none;
            color: black;
            background: yellow;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td align="right">
                    <asp:ImageButton ID="exceleat" runat="server" ImageUrl="~/excel.png" OnClick="btnExportExcel_Click" />
                    <asp:ImageButton ID="wordeat" runat="server" ImageUrl="~/word.png" OnClick="btnWord_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    <div class="GridviewDiv">
                        <asp:GridView ID="gridliste" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                            AllowSorting="true" Width="540px" PageSize="5" CssClass="Gridview" DataKeyNames="id"
                            OnPageIndexChanging="gridliste_PageIndexChanging">
                            <HeaderStyle BackColor="#df5015" />
                            <Columns>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect" runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField DataField="ad" HeaderText="Öğrenci Adı" ItemStyle-Width="40px" />
                                <asp:BoundField DataField="sinif" HeaderText="Sınıfı" ItemStyle-Width="120px" />
                                <asp:BoundField DataField="tcno" HeaderText="Tc.NO" ItemStyle-Width="130px" />
                                <asp:BoundField DataField="adres" HeaderText="Adresi" ItemStyle-Width="130px" />
                            </Columns>
                        </asp:GridView>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

excelwordgridview
GridView içindeki bilgileri çekeceğimiz veritabanı bağlantısını ve gridview içinde seçili olan satırları excel veya word’e aktarmak içinde aşağıdaki satıları yazıyoruz.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridDoldur();
            }
        }
        private void GridDoldur()
        {
            SqlConnection con = new SqlConnection("Data Source=L1-PCOGRETMEN\\SQLEXPRESS;Initial Catalog=ogrenci1;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("select * from kayit", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            gridliste.DataSource = ds;
            gridliste.DataBind();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
           
        }
        protected void gridliste_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SaveCheckedValues();
            gridliste.PageIndex = e.NewPageIndex;
            GridDoldur();
            PopulateCheckedValues();
        }
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            ExportFunction("attachment;filename=exceldosyasi.xls", "application/vnd.ms-excel");
        }
       
        protected void btnWord_Click(object sender, EventArgs e)
        {
            ExportFunction("attachment;filename=worddosyasi.doc", "application/vnd.ms-word");
        }
     private void ExportFunction(string header, string contentType)
        {
            SaveCheckedValues();
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
            Response.Charset = "windows-1254";
          Response.Buffer = true;
            Response.AddHeader("content-disposition", header);
          Response.ContentType = contentType;
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gridliste.AllowPaging = false;
            GridDoldur();
            gridliste.HeaderRow.Style.Add("background-color", "#FFFFFF");
            gridliste.HeaderRow.Cells[0].Visible = false;
            for (int i = 0; i < gridliste.HeaderRow.Cells.Count; i++)
            {
                gridliste.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
                gridliste.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
            }
            if (ViewState["CHECKED_ITEMS"] != null)
            {
                ArrayList CheckBoxArray = (ArrayList)ViewState["CHECKED_ITEMS"];
                int rowIdx = 0;
                for (int i = 0; i < gridliste.Rows.Count; i++)
                {
                    GridViewRow row = gridliste.Rows[i];
                    row.Visible = false;
                    int index = (int)gridliste.DataKeys[row.RowIndex].Value;
                    if (CheckBoxArray.Contains(index))
                    {
                        row.Visible = true;
                        row.Cells[0].Visible = false;
                    }
                }
            }
            gridliste.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.End();
        }
        
        private void PopulateCheckedValues()
        {
            ArrayList userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
            if (userdetails != null && userdetails.Count > 0)
            {
                foreach (GridViewRow gvrow in gridliste.Rows)
                {
                    int index = (int)gridliste.DataKeys[gvrow.RowIndex].Value;
                    if (userdetails.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }
      
        private void SaveCheckedValues()
        {
            ArrayList userdetails = new ArrayList();
            int index = -1;
            foreach (GridViewRow gvrow in gridliste.Rows)
            {
                index = (int)gridliste.DataKeys[gvrow.RowIndex].Value;
                bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;
                // Check in the Session
                if (ViewState["CHECKED_ITEMS"] != null)
                    userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
                if (result)
                {
                    if (!userdetails.Contains(index))
                        userdetails.Add(index);
                }
                else
                    userdetails.Remove(index);
            }
            if (userdetails != null && userdetails.Count > 0)
                ViewState["CHECKED_ITEMS"] = userdetails;
        }

You do not have the latest version of Flash installed. Please visit this link to download it: http://www.adobe.com/products/flashplayer/

You may also like...

Subscribe
Bildir
guest
4 Yorum
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
öğrenci

Sitenizde ya iletişim kısmı yok yada ben görmedim. neyse benim dicegim bu konuyla alakalı değil buraya yazmak zorunda kaldım bilgisayar programcılığı öğrencisiyim bi çok proje ödevimi siteniz yardımıyla yaptım. teşekkür ederim emeginiz için. bi ödev verildi web sayfadaki yazıya yorum yapma özelliği ekleme diye, rica etsem o konu hakkında bilginiz varsa onu anlatır mısınız?

BilisimOgretmeni

Öncelikle ilginiz için teşekkürler, evet iletişim bölümü yok du yeni ekledim , ayrıca istediğiniz tarzda bir derste sitemize eklendi Asp.Net Yorum Sistemi adresinden inceleyebilirsiniz.

Mesut

Merhaba dışarı aktarılan excellerde dosyayı açarken dosyanın uzantısıyla aynı yapıda olmadığıyla alakalı uyarı veriyor bu sorunun çözümünü bulamadım hiç bir yerde.. dışarı aktarılan excelin içeriğini başka bir excel dosyasını masaüstünde yeni oluştur şeklinde oluşturarak içine kopyaladağımda sorun çıkmıyor.. Sorun asp.net ile oluşturduğumuz excel den kaynaklanıyor.. Bunu nasıl çözebiliriz ??

hkn-ysf

Sanırsam kodlarda bir sıkıntı var. Çalıştıramadım.
DataBinding: ‘System.Data.DataRowView’, id adında bir özellik içermiyor. alıyorum. Mümkünse proje dosyasını gönderebilir misiniz

4
0
Yazı hakkındaki yorum, görüş ve önerilerinizi yazınx
()
x