导出到Excel - 将DateTime列设置为Date

时间:2016-11-28 16:11:24

标签: excel vb.net datetime format export

我的应用程序中有一个导出到Excel功能。 程序本身没有问题,但在导出数据时,它会将DateTime值显示为dd/MM/yyyy 00:00:00,在导入前在DataGridView上显示它们时,会在某些地方显示空单元格

我需要调整导出代码以删除数据的时间部分,然后只显示日期。当我在Excel中突出显示单元格时,我将其格式化为'日期'格式为dd/MM/yyyy

我该如何以编程方式执行此操作?

我的代码

Dim xlapp As Excel.Application
Dim xlWorkbook As Excel.Workbook
Dim xlWorksheet As Excel.Worksheet
Dim misvalue As Object = Reflection.Missing.Value

xlapp = New Excel.Application
xlWorkbook = xlapp.Workbooks.Add(misvalue)
xlWorksheet = xlWorkbook.Sheets.Add
xlWorksheet.Name = "SupplierInformation"
xlWorksheet.Cells.NumberFormat = "@"

  For k As Integer = 1 To dgvExport.Columns.Count
    xlWorksheet.Cells(1, k) = dgvExport.Columns(k - 1).HeaderText
  Next

  For i = 0 To dgvExport.RowCount - 1
    For j = 0 To dgvExport.ColumnCount - 1
       xlWorksheet.Cells(i + 2, j + 1) = dgvExport(j, i).Value.ToString
     Next
   Next

xlWorksheet.Columns.AutoFit()

1 个答案:

答案 0 :(得分:1)

  • 声明将用于引用范围的变量,例如;

Dim eRange as Excel.Range

  • 然后,在Worksheet
  • 中设置范围

eRange = xlWorksheet.Range("A1", B5")

  • 然后使用.NumberFormat
  • 设置格式

eRange.NumberFormat = "dd/MM/yyyy"

仅供参考: This link包含有关如何使用VB格式化Excel数据和单元格所需的所有信息