【问题标题】:Export Gridview to Excel with rows formatted as text将 Gridview 导出到 Excel,并将行格式化为文本
【发布时间】:2009-09-01 15:39:41
【问题描述】:

我已经阅读了一些在线教程,但似乎遗漏了一些东西。我试图通过将格式设置为文本来让前导 0 显示在列中。

任何建议将不胜感激。

    ''' <summary>
    ''' This is required for the grid view to export properly
    ''' </summary>
    ''' <param name="control"></param>
    ''' <remarks></remarks>
    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
    End Sub

    Protected Overrides Sub OnInitComplete(ByVal e As System.EventArgs)

            Dim List As System.Web.UI.WebControls.GridView = CType(Page.FindControl("List"), System.Web.UI.WebControls.GridView)
            AddHandler List.RowDataBound, AddressOf RowDataBound

            List.DataSource = myList
            List.DataBind()

            Response.Clear()
            Response.ContentType = "application/vnd.ms-excel"
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=ExportList.xls")

            Response.Write("<style> .text {mso-number-format:\@; } </style>")

            Using strwriter As New System.IO.StringWriter
                Using htmlwriter As New HtmlTextWriter(strwriter)

                    List.RenderControl(htmlwriter)

                    HttpContext.Current.Response.Write(strwriter.ToString)
                    HttpContext.Current.ApplicationInstance.CompleteRequest()
                End Using
            End Using

    End Sub

    Protected Sub RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)

        If e.Row.RowType = DataControlRowType.DataRow Then

            e.Row.Cells(0).Attributes.Add("class", "text")

            Dim dtview As System.Data.DataRowView
            Dim dt As DateTime
            Dim intCounter As Integer

            dtview = e.Row.DataItem

            For intCounter = 0 To dtview.Row.ItemArray.Length - 1

                If TypeOf dtview.Row.Item(intCounter) Is System.DateTime Then
                    dt = dtview.Row.Item(intCounter)
                    e.Row.Cells(intCounter).Text = dt.ToLongDateString
                End If

            Next
        End If

    End Sub

【问题讨论】:

    标签: asp.net vb.net gridview formatting export-to-excel


    【解决方案1】:

    有一种更好的方法可以达到相同的效果,只需添加一行就可以了。 不要使用循环创建样式表并为所有 &lt;TD&gt; 标签添加属性,而是直接在所有 TD 标签上应用样式。

    string style = @"<style> TD { mso-number-format:\@; } </style>";
    

    【讨论】:

    • 这确实有效。就我而言,它会阻止某些数字格式在 Excel 中显示为日期。字符串仍然可以正常显示为文本。
    【解决方案2】:

    看看这个:how to Export GridView To Word Excel PDF and CSV documents

    它工作正常。非常好。谢谢

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 1970-01-01
      • 2014-12-28
      • 2018-04-18
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多