【问题标题】:Remove time when exported to pdf导出为 pdf 时删除时间
【发布时间】:2020-05-28 04:16:06
【问题描述】:

我的 datagridview 在 datePurchased 列中没有时间。但是当我将它导出为 PDF 时,它已经包含了时间。我只需要日期而不是时间。下面是示例代码

 //For exporting to pdf

      Private Sub ExportButton_Click(sender As Object, e As  EventArgs) Handles ExportButton.Click
  connection.Close()
  connection.Open()

  Dim pdfTable As New PdfPTable(ReportDataGridView.ColumnCount)
  pdfTable.DefaultCell.Padding = 1
  pdfTable.WidthPercentage = 100
  pdfTable.DefaultCell.HorizontalAlignment = Element. ALIGN_CENTER

  Dim ptable As New  Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK)

    For Each column As DataGridViewColumn in ReportDataGridView.Columns
  Dim cell as new PdfPCell(New Phrase(New Chunk(column.HeaderText, ptable)))
  cell.HorizontalAlignment = Element.ALIGN_CENTER
  cell.FixedHeight = 30
  pdfTable.AddCell(cell)

  Next

    For Each row as DataGridViewRow In ReportDataGridView.Rows
  For each cell as DataGridViewCell In row.Cells
  pdfTable.AddCell(cell.Value.ToString)
  Next
  Next

 Dim folderpath As String = "C:\PDFs\"
 If Not Directory.Exists(folderpath) Then
      Directory.CreateDirectory(folderpath)
 End If

  Using sfd as New 
SaveFileDialog()
 sfd.ShowDialog()
 sfd.OverWritePrompt = True
 sfd.Title =" Save As"
 sfd.AddExtension = True
 sfd.DefaultExt = ".pdf"

  Using stream As New FileStream(sfd.FileName & ".pdf", 
   FileMode.Create)
  Dim pdfdoc As New 
  Document (PageSize.LETTER, 36.0F, 36.0F,36.0F,36.0F)
  PdfWriter.GetInstance(pdfdoc.stream)
  pdfdoc.Open()
  pdfdoc.Add(pdfTable)
  pdfdoc.Close()
  stream.Close()
  If File.Exists("path") Then
       File.AppendAllText("path", "contents")
   End If
  pdfdoc.Close()
  stream.Close()
  End Using

  End Using
  End Sub

如果你要问我 DatePurchased 的数据类型是什么,那就是 date。我使用日期而不是日期时间。请帮忙!

【问题讨论】:

  • 日期和时间与同一个概念相关 - 表示未来/历史中的时刻 - 基础类型是 DateTime 并且始终具有日期和时间。在您的网格中,您只能看到日期时间的日期部分,因为这是您的所有网格文本框正在格式化以显示(它显示 MM/dd/yyyy 或其他),尽管日期时间的时间部分仍然存在。发出值时必须应用相同的格式

标签: vb.net sql-server-2017-express


【解决方案1】:

您必须检测日期并在没有时间的情况下明确格式化,例如

For each cell as DataGridViewCell In row.Cells
    Dim cellValue = cell.Value

    pdfTable.AddCell(If(TypeOf cellValue Is Date,
                        CDate(cellValue).ToShortDateString(),
                        cellValue.ToString()))
Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多