Search code examples
asp.netexcelvb.netepplus

Not able to get column datatype


I am trying to loop through the following code to find DateTime columns. I'm not able to get the code to work. Am I missing something? Thanks.

dGrid.DataSource = dSets.Tables(0)
dGrid.DataBind()
ws.Cells(1, 1).LoadFromDataTable(dGrid.DataSource, True)
For i As Byte = 1 To dGrid.Columns.Count
    If dSets.Tables(0).Columns(i).DataType Is GetType(DateTime) Then
        ws.Column(i).Style.Numberformat.Format = "mm/dd/yyyy hh:mm"
    End If
Next

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition"; attachment)
Response.Charset = ""

Solution

  • Almost there, but need the following changes:

    1. Get the column count from DataSource.
    2. Fix collection indexing.

    Tested and working:

    dataGrid.DataSource = dataSet.Tables(0)
    dataGrid.DataBind()
    ws.Cells(1, 1).LoadFromDataTable(dataGrid.DataSource, True)
    Dim data = dataGrid.DataSource
    ' get column count from DataSource: dGrid.Columns.Count is 0
    Dim columnCount = data.Columns.Count
    For i = 0 To columnCount - 1
        If data.Columns(i).DataType Is GetType(DateTime) Then
            ws.Column(i + 1).Style.Numberformat.Format = "mm/dd/yyyy hh:mm"
        End If
    Next