将GridView数据导出到Excel

时间:2014-05-29 12:03:50

标签: asp.net vb.net gridview

您好我试图将gridview数据导出到excel这里是我的代码的一部分,并且它创建了文件但是当我打开文件时exel说它不是exl文件,当我强行打开时它会根据需要显示信息(在网格旁边的空白区域)我旁边的代码,我注意到它捕获了一个expt,其中有这样的内容:

"'ctl00_ContentPlaceHolder1_approvalGrid' 'GridView' runat=server."它谈论标签类型和推杆(它有点凌乱,因为它以我的语言显示)

代码隐藏:

 Protected Sub exportExelBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exportExelBtn.Click    
    If approvalGrid.Rows.Count > 0 Then
            Try    

                Response.ClearContent()
                Response.Buffer = True
                Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "poView.xls"))
                Response.ContentEncoding = Encoding.UTF8
                Response.ContentType = "application/ms-excel"
                ' Dim sw As New stringwriter()
                Dim tw As New IO.StringWriter()
                Dim htw As New HtmlTextWriter(tw)
                approvalGrid.RenderControl(htw)
                Response.Write(tw.ToString())
                Response.[End]()

            Catch ex As Exception

            End Try
  END IF
 END SUB

标记:

 <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="PoViewTable.aspx.vb" Inherits="PoViewTable" %>

    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

                    <asp:GridView ID="approvalGrid" runat="server" AllowSorting="True" 
                AutoGenerateColumns="False" DataSourceID="poViewSql" Visible="False">
                <Columns>
                    <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" 
                        ReadOnly="True" SortExpression="id" />
                    <asp:BoundField DataField="poID" HeaderText="poID" SortExpression="poID" visible = "false"/>
                    <asp:BoundField DataField="companyID" HeaderText="companyID" 
                        SortExpression="companyID" />
                    <asp:BoundField DataField="requesterID" HeaderText="requesterID" 
                        SortExpression="requesterID" />
                    <asp:BoundField DataField="departmentID" HeaderText="departmentID" 
                        SortExpression="departmentID" />
                    <asp:BoundField DataField="subDepartmentID" HeaderText="subDepartmentID" 
                        SortExpression="subDepartmentID" />
                    <asp:BoundField DataField="date" HeaderText="date" SortExpression="date" />
                    <asp:BoundField DataField="amount" HeaderText="amount" 
                        SortExpression="amount" />
                    <asp:BoundField DataField="supplierID" HeaderText="supplierID" 
                        SortExpression="supplierID" />
                    <asp:BoundField DataField="comments" HeaderText="comments" 
                        SortExpression="comments" />
                    <asp:BoundField DataField="managerID1" HeaderText="managerID1" 
                        SortExpression="managerID1" />
                    <asp:BoundField DataField="managerStatus1" HeaderText="managerStatus1" 
                        SortExpression="managerStatus1" />
                    <asp:BoundField DataField="managerID2" HeaderText="managerID2" 
                        SortExpression="managerID2" />
                    <asp:BoundField DataField="managerStatus2" HeaderText="managerStatus2" 
                        SortExpression="managerStatus2" />
                    <asp:BoundField DataField="poStatus" HeaderText="poStatus" 
                        SortExpression="poStatus" />
                </Columns>
            </asp:GridView>
            <br />

...
...   

</asp:Content>

3 个答案:

答案 0 :(得分:0)

请在代码中添加此功能。

 Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    ' Verifies that the control is rendered
End Sub

有关详细信息,请访问。here

或者您可以使用其他方法将gridview导出为ex​​cel

Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    ' Confirms that an HtmlForm control is rendered for the specified ASP.NET
'           server control at run time.     

End Sub

Protected Sub Button1_Click(sender As Object, e As EventArgs)


    Using sw As New StreamWriter("c:\test.xls")
        Using hw As New HtmlTextWriter(sw)
            GridView1.RenderControl(hw)
        End Using
    End Using

End Sub

答案 1 :(得分:0)

此代码有效,只需修改,尊重

Dim sb As StringBuilder = New StringBuilder() 
Dim SW As System.IO.StringWriter = New System.IO.StringWriter(sb) 
Dim htw As HtmlTextWriter = New HtmlTextWriter(SW)
Dim Page As Page = New Page() 
Dim form As HtmlForm = New HtmlForm()
Me.GridView.EnableViewState = False
Page.EnableEventValidation = False
Page.DesignerInitialize() 
Page.Controls.Add(form) 
form.Controls.Add(Me.GridView)
Page.RenderControl(htw)
Response.Clear()
Response.Buffer = True 
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", "attachment;filename=data.xls") Response.Charset = "UTF-8"
Response.ContentEncoding = Encoding.Default
Response.Write(sb.ToString())
Response.End()

答案 2 :(得分:0)

有几点需要注意。

您正在捕捉异常,但您没有对它们采取任何措施。那是code smell。不要这样做。永远。记录异常,或创建通知消息。不要吞下它。

您实际上并未创建Excel文件。您正在创建HTML并为其提供Excel扩展。这就是Excel为什么吓坏了的原因。 Excel知道如何阅读HTML表格,但由于它是错误的扩展名,它想要与您核实它可以做到这一点。这里发布的其他答案都没有解决这个问题。

通常,使用HTML将数据导出为ex​​cel是一个坏主意。您无法轻松控制输出,并且很难避免打开文件时收到的警告消息。

当您向Stack Overflow发布错误时,包含所有相关详细信息。你从来没有真正告诉我们异常的名称,或者是哪一行抛出它。这是重要的信息。

相反,您应该使用专门用于将数据导出到Excel的库。而不是导出GridView,您应该导出基础数据。我最喜欢的图书馆是EPPlus。创建一个实际的.xlsx(Open Office XML电子表格)文件是非常简单的,您可以使用良好的格式。