如何从gridview导出excel? [英] How to export excel from gridview?

查看:76
本文介绍了如何从gridview导出excel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.....我在嵌套gridview中有一个数据,比如点击'+'它会扩展...我想从网格中导出excel的方式相同..





如果我点击'+'我想看excel中的详细信息..



可以任何一个帮助...



我尝试过:



Hi.....I have a data in nested gridview like when clicking '+' it will expand...the same way i want to export the excel from grid..


If I'm clicking '+' i want to see details in excel also..

Can any one help for this...

What I have tried:

public override void VerifyRenderingInServerForm(Control control)
      {
          //required to avoid the run time error "
          //Control 'GridView1' of type 'Grid View' must be placed inside a form tag with runat=server."
      }







protected void BtnexportExcel(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Charset = "";
            string FileName = "Report" + DateTime.Now + ".xls";
            StringWriter strwritter = new StringWriter();
            HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
            GvDetailPrimary.GridLines = GridLines.Both;
            GvDetailPrimary.HeaderStyle.Font.Bold = true;
            GvDetailPrimary.RenderControl(htmltextwrtter);
            Response.Write(strwritter.ToString());
            Response.End();

        }

推荐答案

使用ASP.Net C#将Gridview导出到Excel [ [ ^ ]


OP评论说解决方案1的链接中的示例没有不行。我已经证实这一点。 Excel加载但不会导出网格中的数据。



我不能解决为什么该版本不能正常工作所以这里是另一种选择/>
使用C#和VB.Net格式化将ASPView导出到ASP.Net中的Excel [ ^ ]

(我已验证此代码有效,但我不得不手动添加 OnPageIndexChanging 事件 - 不知道为什么)



这是我的完整代码:

OP has commented that the example in the link from Solution 1 doesn't work. I have confirmed this. Excel loads but the data from the grid is not exported.

I can't be bothered to work out why that version is not working so here is an alternative
Export GridView to Excel in ASP.Net with Formatting using C# and VB.Net[^]
(I've verified that this code works, but I had to manually add the OnPageIndexChanging event - not sure why)

Here is my full code that worked:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test</title>
</head>
<body>

<form runat="server" id="form1">
    <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"

        RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"

        runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging">
        <Columns>
            <asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
            <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
            <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
        </Columns>
    </asp:GridView>

    <br />
    <asp:Button ID="btnExport" runat="server" Text="Export To Excel" OnClick = "Button1_Click" />
    
</form>
</body>
</html>




using System;
using System.IO;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication4
{
    public partial class Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        public override void VerifyRenderingInServerForm(Control control)  
        {  
             //required to avoid the run time error "  
             //Control 'GridView1' of type 'Grid View' must be placed inside a form tag with runat=server."  
        }  
        private void ExportGridToExcel()  
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";

            using (var sw = new StringWriter())
            {
                var hw = new HtmlTextWriter(sw);

                //To Export all pages
                GridView1.AllowPaging = false;

                BindGrid();

                GridView1.HeaderRow.BackColor = Color.White;

                foreach (TableCell cell in GridView1.HeaderRow.Cells)
                {
                    cell.BackColor = GridView1.HeaderStyle.BackColor;
                }

                foreach (GridViewRow row in GridView1.Rows)
                {
                    row.BackColor = Color.White;

                    foreach (TableCell cell in row.Cells)
                    {
                        cell.BackColor = row.RowIndex % 2 == 0 ? GridView1.AlternatingRowStyle.BackColor : GridView1.RowStyle.BackColor;
                        cell.CssClass = "textmode";
                    }
                }

                GridView1.RenderControl(hw);

                //style to format numbers to string
                const string style = @"<style> .textmode { } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }   
        }  
        private void BindGrid()
        {
            var constr = ConfigurationManager.ConnectionStrings["ConnectToDB"].ConnectionString;

            using (var con = new SqlConnection(constr))
            {
                using (var cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
                {
                    using (var sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (var dt = new DataTable())
                        {
                            sda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ExportGridToExcel();  
        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindGrid();
        }
    }
}


这篇关于如何从gridview导出excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆