Exporting GridView into Excel/CSV Not Working

风流意气都作罢 提交于 2020-01-25 07:19:30

问题


i have spent the last 2 days trying to figure out why i am not able to export a very simple gridview into either Excel file or CSV file. When i click the export button, nothing happens and i am not getting any error. At first i tried a code that exports into excel but did not work and now i am trying this code that exports into csv file and it does not work either. Can someone please help? thanks: Here is the markup:

<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>

Here is the code behind:

 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 */
    }

回答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



回答2:


everything is working fine now but it was my mistake that i forgot to add the click even for the button so that is why it was not doing anything. thanks all




回答3:


You could try using these commands to export a DataSet to 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();
}

Please note that this is more of an implementation for the desktop, so you'll have to change it for use with your we application. For more details, please see:

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



来源:https://stackoverflow.com/questions/14651907/exporting-gridview-into-excel-csv-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!