【问题标题】:Exporting GridView into Excel/CSV Not Working将 GridView 导出到 Excel/CSV 不起作用
【发布时间】:2015-11-25 01:56:18
【问题描述】:

过去 2 天我一直在试图弄清楚为什么我无法将非常简单的 gridview 导出到 Excel 文件或 CSV 文件中。当我单击导出按钮时,什么也没有发生,我没有收到任何错误。起初我尝试了一个导出到 excel 但没有工作的代码,现在我正在尝试这个导出到 csv 文件的代码,它也不起作用。有人可以帮忙吗?谢谢: 这是标记:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        CellPadding="4"  ForeColor="#333333" 
        GridLines="None">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:BoundField DataField="GroupCategory" HeaderText="GroupCategory" 
            SortExpression="GroupCategory" />
        <asp:BoundField DataField="TotalCount" HeaderText="TotalCount" 
            SortExpression="TotalCount" />
    </Columns>
    <EditRowStyle BackColor="#7C6F57" />
    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#E3EAEB" />
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F8FAFA" />
    <SortedAscendingHeaderStyle BackColor="#246B61" />
    <SortedDescendingCellStyle BackColor="#D4DFE1" />
    <SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>

下面是代码:

 public void BindData()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
        SqlDataAdapter da = new SqlDataAdapter("SELECT [GroupCategory], [TotalCount] FROM [Test] ", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        // GV_InlineEditing.DataBind();
        this.GridView1.DataBind();
    }

    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
         "attachment;filename=GridViewExport.csv");
        Response.Charset = "";
        Response.ContentType = "application/text";

        GridView1.AllowPaging = false;
        GridView1.DataBind();

        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Columns[k].HeaderText + ',');
        }
        //append new line
        sb.Append("\r\n");
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                //add separator
                sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
            }
            //append new line
            sb.Append("\r\n");
        }
        Response.Output.Write(sb.ToString());
        Response.Flush();
        Response.End();

    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

【问题讨论】:

  • 看来您需要在导出前再次调用BindData()。
  • 在您的导出代码中,将GridView1.DataBind(); 替换为BindData();
  • EJC,我做到了,它没有导出任何东西。当我单击按钮时,它什么也不做。我看到页面在闪烁,但没有其他内容
  • 现在挖掘一些代码。

标签: c# asp.net gridview


【解决方案1】:
Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView, Optional ByVal IncludeFooter As Boolean = True)

        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
        HttpContext.Current.Response.Charset = "UTF-8"
        Dim sw As StringWriter = New StringWriter
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        '  Create a form to contain the grid
        Dim table As Table = New Table
        '  add the header row to the table
        If (Not (gv.HeaderRow) Is Nothing) Then
            myGridview.PrepareControlForExport(gv.HeaderRow)
            table.Rows.Add(gv.HeaderRow)
        End If
        '  add each of the data rows to the table
        For Each row As GridViewRow In gv.Rows
            myGridview.PrepareControlForExport(row)
            table.Rows.Add(row)
        Next
        '  add the footer row to the table
        If IncludeFooter Then
            If (Not (gv.FooterRow) Is Nothing) Then
                myGridview.PrepareControlForExport(gv.FooterRow)
                table.Rows.Add(gv.FooterRow)
            End If
        End If
        '  render the table into the htmlwriter
        table.RenderControl(htw)
        '  render the htmlwriter into the response
        HttpContext.Current.Response.Write(Replace(sw.ToString, "'", "''"))

        HttpContext.Current.Response.End()
    End Sub

    ' Replace any of the contained controls with literals
    Private Shared Sub PrepareControlForExport(ByVal control As Control)
        Dim i As Integer = 0
        Do While (i < control.Controls.Count)
            Dim current As Control = control.Controls(i)
            If (TypeOf current Is LinkButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
            ElseIf (TypeOf current Is ImageButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
            ElseIf (TypeOf current Is HyperLink) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
            ElseIf (TypeOf current Is DropDownList) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
            ElseIf (TypeOf current Is CheckBox) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
                'TODO: Warning!!!, inline IF is not supported ?
            End If
            If current.HasControls Then
                myGridview.PrepareControlForExport(current)
            End If
            i = (i + 1)
        Loop
    End Sub

【讨论】:

  • 哎呀——那是 VB——但你应该可以在上面使用转换器,或者如果你只是想自己做的话,就很简单了。
  • 我在这段代码中遇到了很多错误。我转换为 C#,但似乎转换不正确。是因为某种原因跳过了很多代码。很奇怪
  • 对不起,我在 VB 中经常使用它——不确定 C# 转换发生了什么。原则上,您可能只是将其用作指南 - 主要功能就是:for each row in gridview.rows,然后用它做一些事情(将其放入您可以稍后呈现 html 的表中,将其放入一个字符串变量中您可以稍后导出到 .csv,或者您有什么。)
【解决方案2】:

现在一切正常,但我忘记为按钮添加点击是我的错误,所以这就是它没有做任何事情的原因。谢谢大家

【讨论】:

    【解决方案3】:

    您可以尝试使用这些命令将数据集导出到 Excel:

    public void ConvertDataSetToExcel(DataSet dataSet, string strTempFileName)
    {
        XmlDocument xmlDataDoc = null;
        XslCompiledTransform xslTransform = new XslCompiledTransform();
        StreamReader srrReader = null;
    
        XmlTextReader xtrRdr = null;
        StringWriter stwWriter = null;
        StreamWriter srwWriter = null;
    
        xmlDataDoc = new XmlDocument();
        xmlDataDoc.LoadXml(dataSet.GetXml());
        srrReader = new StreamReader(path_to_embedded_xsl);
        xtrRdr = new XmlTextReader(srrReader);
        stwWriter = new StringWriter();
        xslTransform.Transform(xmlDataDoc, null, stwWriter);
        xslTransform.Transform(xmlDataDoc, null, stwWriter);
        srwWriter = new StreamWriter(strTempFileName);
        srwWriter.Write(stwWriter.ToString());
        srwWriter.Close();
    }
    

    请注意,这更多是针对桌面的实现,因此您必须对其进行更改以用于您的 we 应用程序。更多详情请见:

    http://www.codeproject.com/Articles/9380/Export-a-DataSet-to-Microsoft-Excel-without-the-ushttp://www.codeproject.com/Articles/11171/DataSet-to-Excel-in-Two-steps-with-Different-Style

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 2013-09-25
      相关资源
      最近更新 更多