我正在尝试让我的代码遍历每个DateTime列并搜索包含" 00:00"小时和分钟。如果值存在,请删除00:00并仅保留日期。对于不包含该值的单元格,请保留单元格。例如,如果" 3/22/2017 00:00",则将其格式化为" 3/22 / 2017"。否则,如果" 3/22/2017 09:16",请不要管它。提前谢谢!
dataGrid.DataSource = dataSet.Tables(0)
dataGrid.DataBind()
ws.Cells(1, 1).LoadFromDataTable(dataGrid.DataSource, True)
Dim data = dataGrid.DataSource
Dim columnCount = data.Columns.Count
For i = 0 To columnCount - 1
If data.Columns(i).DataType Is GetType(DateTime) Then
If Not data.Columns(i).ToString.Contains("00:00") Then
ws.Column(i + 1).Style.Numberformat.Format = "mm/dd/yyyy hh:mm"
Else
ws.Column(i + 1).Style.Numberformat.Format = "mm/dd/yyyy"
End If
End If
Next
答案 0 :(得分:2)
要使您的解决方案正常工作,您需要在每个单元格上设置样式。这是一种效率低下的解决方案,因为将为每个单元格创建样式。可以通过定义两种不同的样式并根据需要将这些引用分配给单元格来减轻某种程度。
更简单的解决方案是使用DataGridView.CellFormatting Event设置绘制单元格时的格式。
显然,DateTime值的时间分量小于一分钟,因为如果不是这种情况,默认格式化将产生所需的结果。下面的代码根据时间分量是否小于一分钟来设置格式。
Private Shared tsLimit As New TimeSpan(0, 1, 0) ' 1 minute
Private Shared dtType As Type = GetType(DateTime)
Private Sub dataGrid_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dataGrid.CellFormatting
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim dt As DataTable = TryCast(dgv.DataSource, DataTable)
If dt IsNot Nothing Then
Dim sourceColumn As DataColumn = dt.Columns.Item(dgv.Columns.Item(e.ColumnIndex).DataPropertyName)
If sourceColumn IsNot Nothing AndAlso sourceColumn.DataType Is dtType AndAlso e.Value IsNot Nothing AndAlso Not e.Value Is DBNull.Value Then
Dim d As DateTime = CDate(e.Value)
If d.TimeOfDay < tsLimit AndAlso d.Hour <> 0 Then
e.CellStyle.Format = "mm/dd/yyyy"
Else
e.CellStyle.Format = "mm/dd/yyyy hh:mm"
End If
End If
End If
End Sub
答案 1 :(得分:1)
这可以通过以下方式实现:
DateTime
列设置默认格式 这是一个处理多个DateTime
列的简单帮助方法:
Sub SetDateTimeStyles(ByRef data As DataTable, ByRef ws As ExcelWorksheet)
' Track DateTime columns to override default column style
Dim dateTimeColumns = New List(Of Integer)()
' Set column format
Dim columnCount = data.Columns.Count
For i = 0 To columnCount - 1
If data.Columns(i).DataType Is GetType(DateTime) Then
Dim epPlusColumn = i + 1
ws.Column(epPlusColumn).Style.Numberformat.Format = "mm/dd/yyyy hh:mm"
dateTimeColumns.Add(epPlusColumn)
End If
Next
' Header row exists; set to 1 if no header row
Dim rowOffset = 2
Dim rowCount = data.Rows.Count
' Only set cell format when hour and minute are **both** zero
For i = 0 To rowCount - 1
For Each dateTimeColumn In dateTimeColumns
Dim value As DateTime = data(i)(dateTimeColumn - 1)
If value.Hour = 0 AndAlso value.Minute = 0 AndAlso value.Second = 0 Then
ws.Cells(i + rowOffset, dateTimeColumn) _
.Style.Numberformat.Format = "mm/dd/yyyy"
End If
Next
Next
End Sub
在创建Excel文件时调用它:
dataGrid.DataSource = dataSet.Tables(0)
dataGrid.DataBind()
ws.Cells(1, 1).LoadFromDataTable(dataGrid.DataSource, True)
Dim data As DataTable = dataGrid.DataSource
SetDateTimeStyles(data, ws)
结果: