2

I have read several tutorials online and seem to be missing something. I am trying to have the leading 0's show up in columns by setting the format to text.

Any suggestions would be appreciated.

    ''' <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
BenMorel
  • 34,448
  • 50
  • 182
  • 322

2 Answers2

6

There is a better way to achieve the same result, just add one line and it will work. Instead of creating style sheet and adding attributes for all <TD> tags using loop, direct apply style on the All TD Tags.

string style = @"<style> TD { mso-number-format:\@; } </style>";
Stephen
  • 1,737
  • 2
  • 26
  • 37
Arun Singh
  • 1,538
  • 4
  • 19
  • 43
  • This really works. In my case it stops some number formats from being displayed as date in excel. Strings still display as text fine. – M H Dec 02 '14 at 16:20
0

Check this out: how to Export GridView To Word Excel PDF and CSV documents

It works fine. Very best. Thanks

LPL
  • 16,827
  • 6
  • 51
  • 95
George
  • 1