这是我使用datagridview查看的MS Access
中的表:
LName FName DateCreated
Cena John 12/25/2011
Parker Peter 7/19/2010
Smith Will 11/11/2009
我可以使用以下代码成功地将我的数据从datagridview转换为CSV文件:
Public Sub ConverToCSVFile(ByVal datagridviewdata As DataGridView)
Try
'Build the CSV file data as a Comma separated string.
Dim csv As String = String.Empty
'Adding the Rows
For Each row As DataGridViewRow In datagridviewdata.Rows
For Each cell As DataGridViewCell In row.Cells
'Add the Data rows.
csv += cell.Value.ToString().Replace(",", ";") & ","c
Next
'Add new line.
csv += vbCr & vbLf
Next
'Exporting to Excel
Dim folderPath As String = "C:CSV"
File.WriteAllText(folderPath & "DataGridViewExport.csv", csv)
MessageBox.Show("Report successfully generated", "CSV File", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
但在转换后,日期将其格式更改为CSV文件,如下所示:
Cena,John,12/25/2011 12:00:00 AM
Parket,Peter,7/19/2010 12:00:00 AM
Smith,Will,11/11/2009 12:00:00 AM
结果应该是这样的:
Cena,John,12/25/2011
Parket,Peter,7/19/2010
Smith,Will,11/11/2009
正如@Nick.McDermaid所指出的,在单元格的Value
上调用ToString
将在没有参数的情况下调用DateTime.ToString
方法,您将获得默认输出吗。如果您想要一个特定的输出,那么您必须调用一个DateTime
类型的特定方法来提供该输出,该方法可以是ToShortDateString
或ToString
,并带有适当的参数。这可能看起来像这样:
Dim cellValue = cell.Value
If TypeOf cellValue Is Date Then
cellText = CDate(cellValue).ToShortDateString()
Else
cellText = cellValue.ToString()
End If