无法获取列数据类型

时间:2017-03-16 17:54:05

标签: asp.net excel vb.net epplus

我正在尝试循环使用以下代码来查找DateTime列。我无法让代码生效。我错过了什么吗?感谢。

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 = ""

2 个答案:

答案 0 :(得分:1)

几乎在那里,但需要进行以下更改:

  1. DataSource获取列数。
  2. 修复集合索引。
  3. 经过测试和工作:

    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
    

答案 1 :(得分:0)

尝试

For i As Byte = 1 To dGrid.Columns.Count
    If dt.Columns[i].DataType Is GetType(DateTime) Then
        ws.Column(i).Style.Numberformat.Format = "mm/dd/yyyy hh:mm"
    End If
Next