0

在过去的两天里,我一直在试图弄清楚为什么我不能将一个非常简单的 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 */
    }
4

3 回答 3

0

您可以尝试使用这些命令将数据集导出到 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();
}

请注意,这更多是针对桌面的实现,因此您必须对其进行更改以与您的应用程序一起使用。更多详情,请参阅:

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

于 2013-02-01T18:30:07.280 回答
0

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

于 2013-02-01T20:11:01.200 回答
0
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
于 2013-02-01T17:49:54.523 回答