Remove time when exported to pdf - vb.net

My datagridview doesn't have the time in datePurchased column. But when I exported it to PDF, it already includes the time. I need only the date not the time. Below is the sample code
//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
If you would ask me what's the data type of DatePurchased, it is date. I used date not datetime. Please help!

You would have to detect dates and explicitly format without time, e.g.
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

Related

Remove the time in Datagridview and when exported to PDF

Please help me guys!
I want the time in Date_Purchased(date) to be removed in datagridview. Because whenever I exported the datagrid in PDF, it has the date and time in it. I only want the date and remove the time especially when exported to PDf.
Here's the sample piece of code.
Public Sub NewInventory()
Dim NI as SqlCommand =con.CreateCommand
NI.CommandText = "Insert into Items_table(Room_ID, PC_Number, Item_Name, Date_Purhased) VALUES (#Room_ID,#PC_Number, #Item_Name, #Date_Purchased);"
NI.Parameters.AddWithValue("#Room_ID", Room_ID)
NI.Parameters.AddWithValue("#PC_Number", PC_Number)
NI.Parameters.AddWithValue("#Item_Name", Item_Name)
NI.Parameters.AddWithValue("#Date_Purchased", DatePurchasedDTP.Value)
NI.ExecuteNonQuery()
MessageBox.Show("New item created.")
End Sub
//for DataGridView
Public Sub GetRoomItems(RoomID As String)
Dim getItems As String = "Select Item_ID, PC_Number,
Item_Name, Date_Purchased WHERE Room_ID=" + RoomID
Dim adapter As New SqlDataAdapter(getItems, connection)
Dim table As New DataTable()
adapter.Fill(table)
InventoryDataGrid.DataSource = table
End Sub
//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
If you would ask me what's the data type of Date_Purchased, it is date. I used date not datetime. And still confused why the time is still in pdf whenever I exported it.
Please help me! Thank you so much
In .NET a Date still has a time component, it's just set to midnight (e.g. 12:00:00). You can read about this here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netframework-4.8
A new object with the same date as this instance, and the time value
set to 00:00:00 midnight (00:00:00).
If you want to display a Date as a string with only the date, you can use Date.ToString() and specify a format which omits the time such as Date.ToString("dd/MM/yyyy"). Alternatively you can use Date.ToShortDateString() which does this but uses the current culture short date string format.
More info here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.8
In your code you are doing this loop:
For Each row as DataGridViewRow In ReportDataGridView.Rows
For each cell as DataGridViewCell In row.Cells
pdfTable.AddCell(cell.Value.ToString)
Next
Next
If you change this to use the underlying DataTable instead of the DataGridView itself you can use the DataColumn.DataType to check when you're using a date:
For Each row as DataRow In DataTable.Rows
For Each item In row.ItemArray
If item.GetType Is GetType("System.DateTime") Then
pdfTable.AddCell(item.ToString("dd/MM/yyyy"))
Else
pdfTable.AddCell(item.Value.ToString)
End If
Next
Next
I'm a bit rusty on the specifc syntax but you should be able to work it out from there.

Skip the first line of the CSV file (Headers) Visual Basic

Like many on here, I am new to programming and mainly focus on web development. I have written a program cobbled together from help on here that works perfectly. I take a CSV file and inject it into an SQL database. I am getting a "MalformedLineException" line exception on the last line of the CSV file and believe it is because the header line is not being skipped.
Would love some help on working out how to skip the first line from my code below:
Private Sub subProcessFile(ByVal strFileName As String)
'This is the file location for the CSV File
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(strFileName)
'removing the delimiter
TextFileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(",")
ProgressBar1.Value = 0
Application.DoEvents()
'variables
Dim TextFileTable As DataTable = Nothing
Dim Column As DataColumn
Dim Row As DataRow
Dim UpperBound As Int32
Dim ColumnCount As Int32
Dim CurrentRow As String()
'Loop To read in data from CSV
While Not TextFileReader.EndOfData
Try
CurrentRow = TextFileReader.ReadFields()
If Not CurrentRow Is Nothing Then
''# Check if DataTable has been created
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
''# Get number of columns
UpperBound = CurrentRow.GetUpperBound(0)
''# Create new DataTable
For ColumnCount = 0 To UpperBound
Column = New DataColumn()
Column.DataType = System.Type.GetType("System.String")
Column.ColumnName = "Column" & ColumnCount
Column.Caption = "Column" & ColumnCount
Column.ReadOnly = True
Column.Unique = False
TextFileTable.Columns.Add(Column)
ProgressBar1.Value = 25
Application.DoEvents()
Next
clsDeletePipeLineData.main()
End If
Row = TextFileTable.NewRow
'Dim Rownum As Double = Row
'If Rownum >= 1715 Then
' MsgBox(Row)
'End If
For ColumnCount = 0 To UpperBound
Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
Next
TextFileTable.Rows.Add(Row)
clsInsertPipeLineData.main(CurrentRow(0).ToString, CurrentRow(1).ToString, CurrentRow(2).ToString, CurrentRow(3).ToString, CurrentRow(4).ToString, CurrentRow(5).ToString, CurrentRow(6).ToString, CurrentRow(7).ToString, CurrentRow(9).ToString)
ProgressBar1.Value = 50
Application.DoEvents()
End If
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
ProgressBar1.Value = 100
Application.DoEvents()
clsMailConfirmation.main()
TextFileReader.Dispose()
MessageBox.Show("The process has been completed successfully")
End Using
"MalformedLineException" says that Line cannot be parsed using the current Delimiters, to fix it, adjust Delimiters so the line can be parsed correctly, or insert exception-handling code in order to handle the line.
Someone encountered similar question, maybe its reply can help you.

Visual Basic DataGridView to PDF Exception Error

Okay I am trying to print a DataGridView to Pdf in Visual Basic.net I keep getting an NullReferenceException was Unhandled error. I need some help please.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
'Creating iTextSharp Table from the DataTable data
Dim pdfTable As New PdfPTable(DataGridView1.ColumnCount)
pdfTable.DefaultCell.Padding = 3
pdfTable.WidthPercentage = 30
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT
pdfTable.DefaultCell.BorderWidth = 1
'Adding Header row
For Each column As DataGridViewColumn In DataGridView1.Columns
Dim cell As New PdfPCell(New Phrase(column.HeaderText))
cell.BackgroundColor = New iTextSharp.text.BaseColor(240, 240, 240)
pdfTable.AddCell(cell)
Next
'Adding DataRow
For Each row As DataGridViewRow In DataGridView1.Rows
For Each cell As DataGridViewCell In row.Cells
**pdfTable.AddCell(cell.Value.ToString())** (this is where the exception is thrown)
Next
Next
'Exporting to PDF
Dim folderPath As String = "C:\Users\mnevi\Documents\testpdf"
If Not Directory.Exists(folderPath) Then
Directory.CreateDirectory(folderPath)
End If
Using stream As New FileStream(folderPath & "DataGridViewExport.pdf", FileMode.Create)
Dim pdfDoc As New Document(PageSize.A2, 10.0F, 10.0F, 10.0F, 0.0F)
PdfWriter.GetInstance(pdfDoc, stream)
pdfDoc.Open()
pdfDoc.Add(pdfTable)
pdfDoc.Close()
stream.Close()
End Using
End Sub
I have marked the code that is throwing the exception above with **. Any assistance is greatly appreciated.
Change this:
For Each cell As DataGridViewCell In row.Cells
**pdfTable.AddCell(cell.Value.ToString())** (this is where the exception is thrown)
Next
To something more like this:
For Each cell As DataGridViewCell In row.Cells
Dim val = If(Not String.IsNullOrEmpty(cell?.Value?.ToString), cell?.Value?.ToString, String.Empty)
pdfTable.AddCell(val)
Next
Without knowing more about the PDF writer you are using I can only assume it is blowing up on a common null reference. With the '?.' operator I am saying if the parent or the child is null equate it the same. So essentially I am checking for nothing and then if it has something, providing it, else giving a blank which at least is something.

Printing images in Crystal Reports from VB.Net

I want to print an image in Crystal Reports. I got some code from the web but the image doesn't show; only the text "ok" on the first column was shown.
Any suggestions would greatly appreciated.
Thanks in advance
Here is my code
Dim myRpt As New ImageReport
Dim txtHeader As CrystalDecisions.CrystalReports.Engine.TextObject = myRpt.Section2.ReportObjects("txtHeader")
txtHeader.Text = "IMAGE AND TEXT"
Dim txtDateNow As CrystalDecisions.CrystalReports.Engine.TextObject = myRpt.Section2.ReportObjects("txtDateNow")
txtDateNow.Text = Format(Now(), "MMMM d, yyyy")
Dim row As DataRow = Nothing
Dim DS As New DataSet
'ADD A TABLE TO THE DATASET
DS.Tables.Add("rp_recipe_cr_image_report")
'ADD THE COLUMNS TO THE TABLE
With DS.Tables(0).Columns
.Add("others_t1", Type.GetType("System.String"))
.Add("image", Type.GetType("System.Byte[]"))
End With
Dim fs As New FileStream("D:\asianporkroll.Jpg", FileMode.Open)
Dim br As New BinaryReader(fs)
Dim lBImageByte As Byte()
lBImageByte = New Byte(fs.Length + 1) {}
lBImageByte = br.ReadBytes(Convert.ToInt32(fs.Length))
row = DS.Tables(0).NewRow
row(0) = "ok"
row(1) = lBImageByte
DS.Tables(0).Rows.Add(row)
br.Close()
fs.Close()
myRpt.SetDataSource(DS)
CrystalReportViewer1.ReportSource = myRpt
CrystalReportViewer1.Refresh()
'DISPOSE OF THE DATASET
DS.Dispose()
DS = Nothing

POI: Cell format for 2000 and above records is corrupted

Can anyone help me on how can I fix this one.
I'm using vb.net 2003 and I've tried to generate a report in Excel using POI, but I have a problem when the records is above 2000, cell formats has been missing or corrupted for the next 2000 and above records. And when I'm opening the generated report and It shows a message of "To many different cell formats" and the next message is "Excel encountered an error and had to remove some formatting to avoid corrupting of workbook. Please re-check you formatting carefully."
Can anyone help me on how to fix it or can anyone else have an another idea for me to format all does cell whether it's 2000 records an above.
The below code is my sample code.
Private Sub btnExtract_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExtract.Click
Try
Dim source As String = Application.StartupPath & "\Sample Template.xls"
Dim sfdialog As New SaveFileDialog
'Save File
sfdialog.Filter = "Excel File | *.xls"
If sfdialog.ShowDialog = DialogResult.OK Then
'Variable Decleration
Dim fileIn As java.io.InputStream = New java.io.FileInputStream(source)
Dim fileOut As java.io.OutputStream = New java.io.FileOutputStream(sfdialog.FileName)
Dim wb As HSSFWorkbook = New HSSFWorkbook(fileIn)
Dim sheet As HSSFSheet = wb.getSheet("Sample Template")
Dim row As HSSFRow
Dim cell As HSSFCell
Dim fileName As String = sfdialog.FileName
'Inputs Data
For rowNum As Integer = 3 To 10000
row = createRowCell(sheet, rowNum)
cell = row.getCell(1)
cell.setCellValue(rowNum - 2)
cell = row.getCell(2)
cell.setCellValue("EN" & rowNum - 2)
cell = row.getCell(3)
cell.setCellValue("TN" & rowNum - 2)
Next
fileIn.close()
wb.write(fileOut)
fileOut.flush()
fileOut.close()
If fileName <> "" Then
If MessageBox.Show("Open Generated Excel?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) = DialogResult.Yes Then
Try
Process.Start(fileName)
Catch ex As Exception
MessageBox.Show("Cannot open file", "Open error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Function createRowCell(ByRef sheet As HSSFSheet, ByVal rowIndex As Int32) As HSSFRow
Dim cellIndex As Int32 = 1
Dim newRow As HSSFRow = sheet.createRow(rowIndex)
Dim commonStyle As HSSFCellStyle = sheet.getWorkbook().createCellStyle()
Dim dateStyle As HSSFCellStyle = sheet.getWorkbook().createCellStyle()
Dim createHelper As HSSFCreationHelper = sheet.getWorkbook().getCreationHelper()
Dim newCell As HSSFCell
commonStyle.setBorderBottom(1)
commonStyle.setBorderTop(1)
commonStyle.setBorderLeft(1)
commonStyle.setBorderRight(1)
newCell = newRow.createCell(cellIndex)
newCell.setCellStyle(commonStyle)
cellIndex += 1
newCell = newRow.createCell(cellIndex)
newCell.setCellStyle(commonStyle)
cellIndex += 1
newCell = newRow.createCell(cellIndex)
newCell.setCellStyle(commonStyle)
Return newRow
End Function
It's probably not be a POI issue. According to this Microsoft KB article, there's a limit to the number of custom formats that can be in one Workbook. The article presents a couple solutions (workarounds, really). Hopefully you can figure something out.
It's now working! just check you formatting if it was not redundant. Like formatting borders of one cell (E.G. right,bottom,left,right). It's nice to format only the top and left border for every cell then add some border format if it was at the end of a row or column (E.G. add border in bottom if it reach the maximum row and add border in right if it was reach the last column of a cell) :D
Here is the equivalent code:
Try
Dim source As String = Application.StartupPath & "\Sample Template.xls"
Dim sfdialog As New SaveFileDialog
'Save File
sfdialog.Filter = "Excel File | *.xls"
If sfdialog.ShowDialog = DialogResult.OK Then
'Variable Decleration
Dim fileIn As java.io.InputStream = New java.io.FileInputStream(source)
Dim fileOut As java.io.OutputStream = New java.io.FileOutputStream(sfdialog.FileName)
Dim wb As HSSFWorkbook = New HSSFWorkbook(fileIn)
Dim sheet As HSSFSheet = wb.getSheet("Sample Template")
Dim row As HSSFRow
Dim cell As HSSFCell
Dim bgStyle As HSSFCellStyle = wb.createCellStyle
Dim rightBorder As HSSFCellStyle = wb.createCellStyle
Dim fileName As String = sfdialog.FileName
Dim records As Integer = 60000
'Inputs Data
bgStyle.setBorderTop(1)
bgStyle.setBorderLeft(1)
rightBorder.setBorderTop(1)
rightBorder.setBorderLeft(1)
rightBorder.setBorderRight(1)
For rowNum As Integer = 3 To records
row = sheet.createRow(rowNum)
If rowNum = records Then bgStyle.setBorderBottom(1)
'1
cell = row.createCell(1)
cell.setCellValue(rowNum - 2)
cell.setCellStyle(bgStyle)
cell = row.createCell(2)
cell.setCellValue("EN" & rowNum - 2)
cell.setCellStyle(bgStyle)
cell = row.createCell(3)
cell.setCellValue("TN" & rowNum - 2)
cell.setCellStyle(bgStyle)
Next
fileIn.close()
wb.write(fileOut)
fileOut.flush()
fileOut.close()
If fileName <> "" Then
If MessageBox.Show("Open Generated Excel?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) = DialogResult.Yes Then
Try
Process.Start(fileName)
Catch ex As Exception
MessageBox.Show("Cannot open file", "Open error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try