将网格视图导出到Excel

时间:2013-06-11 14:57:42

标签: c# excel gridview visual-studio-2012

需要帮助将我的gridview引入excel文档。香港专业教育学院尝试了几个例子,似乎无法做到正确。任何帮助将非常感激。这是我的gridview代码,它是从SQL数据库填充的。

<div>
    <asp:GridView Align="Center" ID="gvResults" AutoGenerateColumns="false" runat="server" Width="608px"
        Style="width: 80%; margin-bottom: 0px" CellPadding="4" ForeColor="#333333" GridLines="None"
        OnRowDataBound="gvResults_RowDataBound">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="imgDataMoreInfo" ImageUrl="T:\Groups\IntResoures\pic\tabpic.jpg" CssClass="img_data_moreinfo" Height="7" Width="7" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Government Name & Address">
                <ItemTemplate>
                    <asp:Label ID="lblGovernmentNameAddress" runat="server" Text=""></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="DOB" HeaderText="DOB" />
            <asp:TemplateField HeaderText="SSFHS Name & Address">
                <ItemTemplate>
                    <asp:Label ID="lblSSFHSNameAddress" runat="server" Text=""></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="ssfhsdob" HeaderText="DOB" />
            <asp:TemplateField HeaderText="Match Status">
                <ItemTemplate>
                    <asp:RadioButtonList ID="rblMatchStatus" runat="server" RepeatDirection="Vertical"></asp:RadioButtonList>
                    <asp:Label ID="lblFirst" CssClass="displayNone" runat="server" />
                    <asp:Label ID="lblSecond" CssClass="displayNone" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#999999" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
</div>

我的导出按钮和事件

<asp:Button ID="btnExportToExcel" OnClick="btnExportToExcel_Click" runat="server" Text="Export to Excel" Width="89px" Font-Size="X-Small" />




 protected void btnExportToExcel_Click(object sender, EventArgs e)
{

}

3 个答案:

答案 0 :(得分:2)

以下是与您的代码相对应的更具体的内容:

 protected void btnExportToExcel_Click(object sender, EventArgs e)
{
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;
    filename=FileName.xls");

    Response.Charset = "";

    // If you want the option to open the Excel file without saving than

    // comment out the line below

    // Response.Cache.SetCacheability(HttpCacheability.NoCache);

    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    gvResults.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();

}

答案 1 :(得分:1)

我上周刚刚这样做了。

以下是您需要在aspx文件中放置的代码(您可以根据自己的喜好玩高度和宽度):

<asp:Button ID="ButtonA" runat="server" height="20px" OnClick="ButtonA_Click" Text="Export me" Width="200px />

在aspx页面顶部的Page部分中插入:

EnableEventValidation="false"

在您的cs文件中,将以下内容放在“protected void Page_Load ...”部分下面:

Protected void ButtonA_Click(object sender, EventArgs e)
{
     Response.Clear();
     Response.AddHeader("content-disposition", "attachment;filename=Filename.xls");
     Response.ContentType = "application/vnd.xlsx";
     System.IO.StringWriter stringWrite = new System.IO.StringWriter();
     System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
     GridView1.RenderControl(htmlWrite);
     Response.Write(stringWrite.ToString());
     Response.End();
}

忽略出现的错误,然后点击“是”。出现错误是因为生成的文件不是纯Excel文件类型。它生成一个文本,即文本。将其保存为电子表格,你就可以了。

答案 2 :(得分:0)

通常在写入excel时为

GridView1.RenderControl(htmlWrite);
 Response.Write(stringWrite.ToString());

只会将其作为html表保存到excel not 二进制文件中。 检查你是否担心。

我的项目也有同样的问题。

,然后

  • 我只是在我的项目文件夹中创建空的xcel文件模板,
  • 然后我将数据写入其中。

    string filePath = Server.MapPath("~/ReportFiles/CenterMemberAddressDifferentReport_" + Emp_Session._UserMasterId + ".xls");
        System.IO.File.Copy(Server.MapPath("~/Images/ExcelTemplate.xls"), filePath, true);
    
            System.Threading.Thread.Sleep(1000);
    
            string driver = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties=Excel 8.0;";
            System.Data.OleDb.OleDbConnection Con = new System.Data.OleDb.OleDbConnection(driver);
            System.Data.OleDb.OleDbCommand Com = Con.CreateCommand();
            System.Data.OleDb.OleDbDataAdapter reader = new OleDbDataAdapter();
            Con.Open();
            DataTable dtSheet = Con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SQL = "";
    
            foreach (DataRow Row in dt1.Rows)
            {
                string values = "";
                for (int ik = 0; ik < dt1.Columns.Count; ik++)
                {
                    if (values != "") values += ",";
                    values += "'" + Row[ik].ToString() + "'";
                }
                SQL = "INSERT INTO [Sheet1$] ([CENTER NAME],[CENTER ADDRESS],[MEMBER ID],[MEMBER NAME],[MEMBER ADDRESS],[MEMBER COUNT]) VALUES(" + values + ")";
                Com.CommandText = SQL;
                Com.ExecuteNonQuery();
            }
            Con.Close();
    
            System.Threading.Thread.Sleep(1000);
    
            System.IO.FileStream stream = System.IO.File.OpenRead(filePath);
            byte[] by = new byte[stream.Length];
            stream.Read(by, 0, by.Length);
            stream.Close();
            System.Threading.Thread.Sleep(1000);
            System.IO.File.Delete(filePath);
    
            Response.OutputStream.Write(by, 0, by.Length);
            Response.End();
    

基本上我是在将同一个excel导入到另一个数据源的情况下并且是非常好的。


希望它能帮助你。请求Plz feedbak。谢谢你的漂亮问题。