Skip the first line of the CSV file (Headers) Visual Basic - vb.net

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.

Related

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in vb.net CSV program

This program is simply reading from a CSV and putting that into a DatagridView table. I am not sure what is causing the error shown below.
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in Minecraft Server Program.exe"
This error points to the line "newrow("Days_remaining") = columns(1)
Also, the CSV is formatted as such:
xX_EpicGamer_Xx,2,2/05/2021,9,6,Player was mean to others and stole lots of diamonds
pewdiepie,3,2/05/2021,4,2,Player swore
Thank you for any help
Public Sub LoadCSVFile()
'If the Input file cannot be found, then give error message And exit this Subroutine.
If Not File.Exists(BansCSVFile) Then
MsgBox("Input CSV File of Item Prices not found: " & BansCSVFile)
Exit Sub
End If
'Set up streamreader and variables for reading through file
Dim srdCSV As New IO.StreamReader("bans.csv", System.Text.Encoding.Default)
Dim sline As String = ""
Do
'Read through each line, separating with the comma and putting each entry into its respective column
sline = srdCSV.ReadLine
If sline Is Nothing Then Exit Do
Dim columns() As String = sline.Split(",")
Dim newrow As DataRow = datatable1.NewRow
newrow("Player") = columns(0)
newrow("Days_remaining") = columns(1)
newrow("Date_started") = columns(2)
newrow("Timespan") = columns(3)
newrow("Rule_broken") = columns(4)
newrow("Extra_info") = columns(5)
datatable1.Rows.Add(newrow)
Loop
srdCSV.Close()
dgvBans.DataSource = datatable1
Me.Text = datatable1.Rows.Count & "rows"
End Sub
Edit:
This new code fixed the issue.
Public Sub LoadCSVFile()
'If the Input file cannot be found, then give error message And exit this Subroutine.
If Not File.Exists(BansCSVFile) Then
MsgBox("Input CSV File of Item Prices not found: " & BansCSVFile)
Exit Sub
End If
'Set up streamreader and variables for reading through file
srdCSV = New IO.StreamReader("bans.csv")
Dim totalrec As Integer = 0
Try
Do Until srdCSV.Peek = -1
'Read through each line, separating with the comma and putting each entry into its respective column
strInputFileLine = srdCSV.ReadLine()
'Split CSV lines where commas are
Dim RecordLineColumns() As String = strInputFileLine.Split(",")
'Create a new row in data table and place data into it from array
Dim newrow As DataRow = datatable1.NewRow
newrow("Player") = RecordLineColumns(0)
newrow("Days_remaining") = RecordLineColumns(1)
newrow("Date_started") = RecordLineColumns(2)
newrow("Timespan") = RecordLineColumns(3)
newrow("Rule_broken") = RecordLineColumns(4)
newrow("Extra_info") = RecordLineColumns(5)
datatable1.Rows.Add(newrow)
totalrec = totalrec + 1
Loop
Catch ex As Exception
MsgBox("Error reading file")
Exit Sub
End Try
srdCSV.Close()
'Me.Text = datatable1.Rows.Count & "rows"
MsgBox("Total input records = " & totalrec)
End Sub
using the Try/Catch syntax
After checking which column has a problem, try verifying the csv file.
I am guessing that the Extra_Info is not necessarily present for every record. I am checking for a length less 5 and exiting but if it has at least 5 we continue but only fill in the last field if the length is 6.
Public Sub LoadCSVFile(BansCSVFile As String)
Dim datatable1 As New DataTable
With datatable1.Columns
.Add("Player")
.Add("Days_remaing")
.Add("Date_started")
.Add("Timespan")
.Add("Rule_broken")
.Add("Extra_Info")
End With
If Not File.Exists(BansCSVFile) Then
MsgBox("Input CSV File of Item Prices not found: " & BansCSVFile)
Exit Sub
End If
Dim lines = File.ReadAllLines(BansCSVFile)
For Each sline In lines
Dim columns() As String = sline.Split(","c)
If columns.Length < 5 Then
MessageBox.Show($"Incomplete data on line {sline}")
Return
End If
Dim newrow As DataRow = datatable1.NewRow
newrow("Player") = columns(0)
newrow("Days_remaining") = columns(1)
newrow("Date_started") = columns(2)
newrow("Timespan") = columns(3)
newrow("Rule_broken") = columns(4)
If columns.Length = 6 Then
newrow("Extra_info") = columns(5)
End If
datatable1.Rows.Add(newrow)
Next
dgvBans.DataSource = datatable1
Me.Text = datatable1.Rows.Count & "rows"
End Sub

How to Parse Text File delimited with ~ into a Datatable or Array in VB.Net

I'm trying to parse the text file into an array or datatable where Lines Starting with D, O, and L are a single Row of data.
There are never more than 1 "L" Lines.
I want to get this into a datatable or 2-dimensional array where the column header names (locations) are
Date {D3}
Customer Name {O2}
Address {O3}
City {O7}
State {O8}
Zipcode {O9}
Reference ID {D17}
Amount {D20}
I tried
TextFieldParser("C:\Users\MyAccount\test.txt")
FileReader.SetDelimiters("~")
But I'm not understanding how to work with the output. Any ideas?
B~AAA~~12/03/19~12/03/19~1~428.51~APV~REF~K8~~
D~AAA~~12/03/19~12/03/19~APV~REF~N~REFUNDCIS~~12/03/19~0~N~N~Y~~~0000244909~~~72.90~~~00~N~0~12/03/19~0~12/03/19~12/03/19~0~K8~~~N~N~0~
O~JOHN DOE~ 1000 NOAKY LN ~~~~DETROIT~MI~31000~~~
L~01~141011~000~00000~000~00~000~~REFUND0000244909JOHN DOE~72.90~N~N~~~N~
D~AAA~~12/03/19~12/03/19~APV~REF~N~REFUNDCIS~~12/03/19~0~N~N~Y~~~0000404236~~~101.42~~~00~N~0~12/03/19~0~12/03/19~12/03/19~0~K8~~~N~N~0~
O~BRUCE DOE~UNIT 1 1000 E MICHIGAN AVE ~~~~DETROIT~MI~31000~~~
L~01~141011~000~00000~000~00~000~~REFUND0000404236BRUCE DOE~101.42~N~N~~~N~
D~AAA~~12/03/19~12/03/19~APV~REF~N~REFUNDCIS~~12/03/19~0~N~N~Y~~~0000436750~~~180.00~~~00~N~0~12/03/19~0~12/03/19~12/03/19~0~K8~~~N~N~0~
O~JOEL DOE~ 100 MICHIGAN AVE ~~~~DETROIT~MI~31000~~~
L~01~141011~000~00000~000~00~000~~REFUND0000436750JOEL DOE~180.00~N~N~~~N~
D~AAA~~12/03/19~12/03/19~APV~REF~N~REFUNDCIS~~12/03/19~0~N~N~Y~~~0000448122~~~74.19~~~00~N~0~12/03/19~0~12/03/19~12/03/19~0~K8~~~N~N~0~
O~JOHN DOE~ 100 MICHIGAN AVE ~~~~DETROIT~MI~31000~~~
L~01~141011~000~00000~000~00~000~~REFUND0000448122JOHN DOE~74.19~N~N~~~N~
First I took the code from MS docs https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.fileio.textfieldparser?view=netcore-3.1
I needed to know how many columns I needed in the datatable.
Private Sub OpCode1()
Dim maxColumnCount As Integer
Using MyReader As New TextFieldParser("C:\Users\xxx\test.txt")
MyReader.TextFieldType = FieldType.Delimited
MyReader.Delimiters = {"~"}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
If currentRow.Count > maxColumnCount Then
maxColumnCount = currentRow.Count
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
MessageBox.Show(maxColumnCount.ToString)
End Sub
Once I had the number of columns needed, I created a DataTable and added the necessary number of columns. Then, where the Example instructed you to handle the row, I added the row to the DataTable. Lastly, I displayed the DataTable in a DataGridView.
Private Sub OPCode()
Dim dt As New DataTable
For i = 1 To 38
dt.Columns.Add(i.ToString)
Next
Using MyReader As New TextFieldParser("C:\Users\xxx\test.txt")
MyReader.TextFieldType = FieldType.Delimited
MyReader.Delimiters = {"~"}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
dt.Rows.Add(currentRow)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
DataGridView1.DataSource = dt
End Sub
More specific to your data...
Private Sub OpCode()
Dim dt As New DataTable
dt.Columns.Add("Date", GetType(Date))
dt.Columns.Add("Customer Name", GetType(String))
dt.Columns.Add("Address", GetType(String))
dt.Columns.Add("City", GetType(String))
dt.Columns.Add("State", GetType(String))
dt.Columns.Add("Zipcode", GetType(String))
dt.Columns.Add("RefID", GetType(String))
dt.Columns.Add("Amount", GetType(Decimal))
Dim DataDate As Date
Dim RefID As String = ""
Dim Amount As Decimal
Using MyReader As New TextFieldParser("C:\Users\maryo\test.txt")
MyReader.TextFieldType = FieldType.Delimited
MyReader.Delimiters = {"~"}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
If currentRow(0) = "D" Then
DataDate = CDate(currentRow(3))
RefID = currentRow(17)
Amount = CDec(currentRow(20))
End If
If currentRow(0) = "O" Then
dt.Rows.Add({DataDate, currentRow(1), currentRow(2), currentRow(6), currentRow(7), currentRow(8), RefID, Amount})
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
DataGridView1.DataSource = dt
End Sub
I assumed that the D row applies to the following O row. I saved the data from the D row in the 3 variables and used it when the next row is read.
Remember collections (including arrays) are zero based in .net.

Split in VB.net

FASTER,WW0011,"CTR ,REURN,ALT TUBING HELIUM LEAK",DEFAULT test,1,3.81,test
I need to get the result of the following line as
Arr(0) =faster
Arr(1) =WW0011
Arr(2) =CTR ,REURN,ALT TUBING HELIUM LEAK
Arr(3) =DEFAULT test
Arr(4) =faster
Arr(5) = 1
Arr(6)=3.81
Arr(7) = test
I tried using split, but the problem is on Arr(2)
could anyone please give me a solution
You could use the TextFieldParser class which will take care of situations like this. Set the HasFieldEnclosedInQuotes property to true. Here is an example from MSDN (slightly altered):
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
'Set this to ignore commas in quoted fields.
MyReader.HasFieldsEnclosedInQuotes = True
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
I use this function alot myself
Private Function splitQuoted(ByVal line As String, ByVal delimeter As Char) As String()
Dim list As New List(Of String)
Do While line.IndexOf(delimeter) <> -1
If line.StartsWith("""") Then
line = line.Substring(1)
Dim idx As Integer = line.IndexOf("""")
While line.IndexOf("""", idx) = line.IndexOf("""""", idx)
idx = line.IndexOf("""""", idx) + 2
End While
idx = line.IndexOf("""", idx)
list.Add(line.Substring(0, idx))
line = line.Substring(idx + 2)
Else
list.Add(line.Substring(0, Math.Max(line.IndexOf(delimeter), 0)))
line = line.Substring(line.IndexOf(delimeter) + 1)
End If
Loop
list.Add(line)
Return list.ToArray
End Function
Use a for loop to iterate the string char by char!

Empty lines appears in datagridview

When I go to add data in first row there is empty lines that appear below my code, why do these lines appear? I need only to add data in one row and save it.
Dim pringdata As String = "SELECT * FROM itemInfo "
Dim sqlconload As New SqlConnection(sqlcon)
Try
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "itemInfo")
Dim rowcount As Integer
rowcount = ds.Tables("itemInfo").Rows.Count
If rowcount >= 1 Then
DGVorders.Rows.Add(rowcount)
For i = 0 To rowcount - 1
If DGVorders.CurrentRow.Cells(0).Value = ds.Tables("itemInfo").Rows(i).Item("itemCode") Then
DGVorders(1, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("itemName")
DGVorders(2, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("Uint1")
DGVorders(4, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("price1")
End If
Next
End If
sqlconload.Close()
Catch ex As Exception
End Try
End Sub
Modify the "AllowUsersToAddRows" property to remove that blank line.
Example:
DataGridView1.AllowUserToAddRows = False
DGVorders.Rows.Add(rowcount) will add rowcount amount of empty rows to your DataGridView. I don't know why you are doing that, it's not as if you are adding values to the cells in those new rows in your for loop.
updated
If dataGridView1.CurrentRow.Cells(0).Value = ds.Tables("itemInfo").Rows(i)("itemCode") Then
Dim newRow As DataGridViewRow = TryCast(dataGridView1.CurrentRow.Clone(), DataGridViewRow)
newRow.Cells(1).Value = ds.Tables("itemInfo").Rows(i)("itemName")
newRow.Cells(2).Value = ds.Tables("itemInfo").Rows(i)("Uint1")
newRow.Cells(3).Value = ds.Tables("itemInfo").Rows(i)("price1")
dataGridView1.Rows.Add(newRow)
End If

How to export datagridview to excel using vb.net?

I have a datagridview in vb.net that is filled up from the database. I've researched and I found out that there is no built in support to print directly from datagridview. I don't want to use crystal report because I'm not familiar with it.
I'm planning to export it to excel to enable me to generate report from the datagridview.
Can you provide me ways to do this?
Code below creates Excel File and saves it in D: drive
It uses Microsoft office 2007
FIRST ADD REFERRANCE (Microsoft office 12.0 object library ) to your project
Then Add code given bellow to the Export button click event-
Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles VIEW_Button.Click
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file D:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
Excel Method
This method is different than many you will see. Others use a loop to write each cell and write the cells with text data type.
This method creates an object array from a DataTable or DataGridView and then writes the array to Excel. This means I can write to Excel without a loop and retain data types.
I extracted this from my library and I think I changed it enough to work with this code only, but more minor tweaking might be necessary. If you get errors just let me know and I'll correct them for you. Normally, I create an instance of my class and call these methods. If you would like to use my library then use this link to download it and if you need help just let me know.
https://zomp.co/Files.aspx?ID=zExcel
After copying the code to your solution you will use it like this.
In your button code add this and change the names to your controls.
WriteDataGrid("Sheet1", grid)
To open your file after exporting use this line
System.Diagnostics.Process.Start("The location and filename of your file")
In the WriteArray method you'll want to change the line that saves the workbook to where you want to save it. Probably makes sense to add this as a parameter.
wb.SaveAs("C:\MyWorkbook.xlsx")
Public Function WriteArray(Sheet As String, ByRef ObjectArray As Object(,)) As String
Try
Dim xl As Excel.Application = New Excel.Application
Dim wb As Excel.Workbook = xl.Workbooks.Add()
Dim ws As Excel.Worksheet = wb.Worksheets.Add()
ws.Name = Sheet
Dim range As Excel.Range = ws.Range("A1").Resize(ObjectArray.GetLength(0), ObjectArray.GetLength(1))
range.Value = ObjectArray
range = ws.Range("A1").Resize(1, ObjectArray.GetLength(1) - 1)
range.Interior.Color = RGB(0, 70, 132) 'Con-way Blue
range.Font.Color = RGB(Drawing.Color.White.R, Drawing.Color.White.G, Drawing.Color.White.B)
range.Font.Bold = True
range.WrapText = True
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
range.Application.ActiveWindow.SplitColumn = 0
range.Application.ActiveWindow.SplitRow = 1
range.Application.ActiveWindow.FreezePanes = True
wb.SaveAs("C:\MyWorkbook.xlsx")
wb.CLose()
xl.Quit()
xl = Nothing
wb = Nothing
ws = Nothing
range = Nothing
ReleaseComObject(xl)
ReleaseComObject(wb)
ReleaseComObject(ws)
ReleaseComObject(range)
Return ""
Catch ex As Exception
Return "WriteArray()" & Environment.NewLine & Environment.NewLine & ex.Message
End Try
End Function
Public Function WriteDataGrid(SheetName As String, ByRef dt As DataGridView) As String
Try
Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
For c As Integer = 0 To dt.Columns.Count - 1
l(0, c) = dt.Columns(c).HeaderText
Next
For r As Integer = 1 To dt.Rows.Count
For c As Integer = 0 To dt.Columns.Count - 1
l(r, c) = dt.Rows(r - 1).Cells(c)
Next
Next
Dim errors As String = WriteArray(SheetName, l)
If errors <> "" Then
Return errors
End If
Return ""
Catch ex As Exception
Return "WriteDataGrid()" & Environment.NewLine & Environment.NewLine & ex.Message
End Try
End Function
Public Function WriteDataTable(SheetName As String, ByRef dt As DataTable) As String
Try
Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
For c As Integer = 0 To dt.Columns.Count - 1
l(0, c) = dt.Columns(c).ColumnName
Next
For r As Integer = 1 To dt.Rows.Count
For c As Integer = 0 To dt.Columns.Count - 1
l(r, c) = dt.Rows(r - 1).Item(c)
Next
Next
Dim errors As String = WriteArray(SheetName, l)
If errors <> "" Then
Return errors
End If
Return ""
Catch ex As Exception
Return "WriteDataTable()" & Environment.NewLine & Environment.NewLine & ex.Message
End Try
End Function
I actually don't use this method in my Database program because it's a slow method when you have a lot of rows/columns. I instead create a CSV from the DataGridView. Writing to Excel with Excel Automation is only useful if you need to format the data and cells otherwise you should use CSV. You can use the code after the image for CSV export.
CSV Method
Private Sub DataGridToCSV(ByRef dt As DataGridView, Qualifier As String)
Dim TempDirectory As String = "A temp Directory"
System.IO.Directory.CreateDirectory(TempDirectory)
Dim oWrite As System.IO.StreamWriter
Dim file As String = System.IO.Path.GetRandomFileName & ".csv"
oWrite = IO.File.CreateText(TempDirectory & "\" & file)
Dim CSV As StringBuilder = New StringBuilder()
Dim i As Integer = 1
Dim CSVHeader As StringBuilder = New StringBuilder()
For Each c As DataGridViewColumn In dt.Columns
If i = 1 Then
CSVHeader.Append(Qualifier & c.HeaderText.ToString() & Qualifier)
Else
CSVHeader.Append("," & Qualifier & c.HeaderText.ToString() & Qualifier)
End If
i += 1
Next
'CSV.AppendLine(CSVHeader.ToString())
oWrite.WriteLine(CSVHeader.ToString())
oWrite.Flush()
For r As Integer = 0 To dt.Rows.Count - 1
Dim CSVLine As StringBuilder = New StringBuilder()
Dim s As String = ""
For c As Integer = 0 To dt.Columns.Count - 1
If c = 0 Then
'CSVLine.Append(Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
s = s & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
Else
'CSVLine.Append("," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
s = s & "," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
End If
Next
oWrite.WriteLine(s)
oWrite.Flush()
'CSV.AppendLine(CSVLine.ToString())
'CSVLine.Clear()
Next
'oWrite.Write(CSV.ToString())
oWrite.Close()
oWrite = Nothing
System.Diagnostics.Process.Start(TempDirectory & "\" & file)
GC.Collect()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DATAGRIDVIEW_TO_EXCEL((DataGridView1)) ' PARAMETER: YOUR DATAGRIDVIEW
End Sub
Private Sub DATAGRIDVIEW_TO_EXCEL(ByVal DGV As DataGridView)
Try
Dim DTB = New DataTable, RWS As Integer, CLS As Integer
For CLS = 0 To DGV.ColumnCount - 1 ' COLUMNS OF DTB
DTB.Columns.Add(DGV.Columns(CLS).Name.ToString)
Next
Dim DRW As DataRow
For RWS = 0 To DGV.Rows.Count - 1 ' FILL DTB WITH DATAGRIDVIEW
DRW = DTB.NewRow
For CLS = 0 To DGV.ColumnCount - 1
Try
DRW(DTB.Columns(CLS).ColumnName.ToString) = DGV.Rows(RWS).Cells(CLS).Value.ToString
Catch ex As Exception
End Try
Next
DTB.Rows.Add(DRW)
Next
DTB.AcceptChanges()
Dim DST As New DataSet
DST.Tables.Add(DTB)
Dim FLE As String = "" ' PATH AND FILE NAME WHERE THE XML WIL BE CREATED (EXEMPLE: C:\REPS\XML.xml)
DTB.WriteXml(FLE)
Dim EXL As String = "" ' PATH OF/ EXCEL.EXE IN YOUR MICROSOFT OFFICE
Shell(Chr(34) & EXL & Chr(34) & " " & Chr(34) & FLE & Chr(34), vbNormalFocus) ' OPEN XML WITH EXCEL
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Regarding your need to 'print directly from datagridview', check out this article on CodeProject:
The DataGridViewPrinter Class
There are a number of similar articles but I've had luck with the one I linked.
The following code works fine for me :)
Protected Sub ExportToExcel(sender As Object, e As EventArgs) Handles ExportExcel.Click
Try
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=ExportEthias.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Using sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GvActifs.RenderControl(hw)
'Le format de base est le texte pour éviter les problèmes d'arrondis des nombres
Dim style As String = "<style> .textmode { } </style>"
Response.Write(Style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
End Using
Catch ex As Exception
lblMessage.Text = "Erreur export Excel : " & ex.Message
End Try
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Hopes this help you.
Dim rowNo1 As Short
Dim numrow As Short
Dim colNo1 As Short
Dim colNo2 As Short
rowNo1 = 1
colNo1 = 1
colNo2 = 1
numrow = 1
ObjEXCEL = CType(CreateObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
objEXCELBook = CType(ObjEXCEL.Workbooks.Add, Microsoft.Office.Interop.Excel.Workbook)
objEXCELSheet = CType(objEXCELBook.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
ObjEXCEL.Visible = True
For numCounter = 0 To grdName.Columns.Count - 1
' MsgBox(grdName.Columns(numCounter).HeaderText())
If grdName.Columns(numCounter).Width > 0 Then
ObjEXCEL.Cells(1, numCounter + 1) = grdName.Columns(numCounter).HeaderText()
End If
' ObjEXCEL.Cells(1, numCounter + 1) = grdName.Columns.GetFirstColumn(DataGridViewElementStates.Displayed)
Next numCounter
ObjEXCEL.Range("A:A").ColumnWidth = 10
ObjEXCEL.Range("B:B").ColumnWidth = 25
ObjEXCEL.Range("C:C").ColumnWidth = 20
ObjEXCEL.Range("D:D").ColumnWidth = 20
ObjEXCEL.Range("E:E").ColumnWidth = 20
ObjEXCEL.Range("F:F").ColumnWidth = 25
For rowNo1 = 0 To grdName.RowCount - 1
For colNo1 = 0 To grdName.ColumnCount - 1
If grdName.Columns(colNo1).Width > 0 Then
If Trim(grdName.Item(colNo1, rowNo1).Value) <> "" Then
'If IsDate(grdName.Item(colNo1, rowNo1).Value) = True Then
' ObjEXCEL.Cells(numrow + 1, colNo2) = Format(CDate(grdName.Item(colNo1, rowNo1).Value), "dd/MMM/yyyy")
'Else
ObjEXCEL.Cells(numrow + 1, colNo2) = grdName.Item(colNo1, rowNo1).Value
'End If
End If
If colNo2 >= grdName.ColumnCount Then
colNo2 = 1
Else
colNo2 = colNo2 + 1
End If
End If
Next colNo1
numrow = numrow + 1
Next rowNo1
In design mode: Set DataGridView1 ClipboardCopyMode properties to EnableAlwaysIncludeHeaderText
or on the program code
DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
In the run time select all cells content (Ctrl+A) and copy (Ctrl+C) and paste to the Excel Program.
Let the Excel do the rest
Sorry for the inconvenient, I have been searching the method to print data directly from the datagridvew (create report from vb.net VB2012) and have not found the satisfaction result.
Above code just my though, wondering if my applications user can rely on above simple step it will be nice and I could go ahead to next step on my program progress.
A simple way of generating a printable report from a Datagridview is to place the datagridview on a Panel object. It is possible to draw a bitmap of the panel.
Here's how I do it.
'create the bitmap with the dimentions of the Panel
Dim bmp As New Bitmap(Panel1.Width, Panel1.Height)
'draw the Panel to the bitmap "bmp"
Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)
I create a multi page tiff by "breaking my datagridview items into pages.
this is how i detect the start of a new page:
'i add the rows to my datagrid one at a time and then check if the scrollbar is active.
'if the scrollbar is active i save the row to a variable and then i remove it from the
'datagridview and roll back my counter integer by one(thus the next run will include this
'row.
Private Function VScrollBarVisible() As Boolean
Dim ctrl As New Control
For Each ctrl In DataGridView_Results.Controls
If ctrl.GetType() Is GetType(VScrollBar) Then
If ctrl.Visible = True Then
Return True
Else
Return False
End If
End If
Next
Return Nothing
End Function
I hope this helps
another easy way and more flexible , after loading data into Datagrid
Private Sub Button_Export_Click(sender As Object, e As EventArgs) Handles Button_Export.Click
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\1\Myfile.csv", True)
If DataGridView1.Rows.Count = 0 Then GoTo loopend
' collect the header's names
Dim Headerline As String
For k = 0 To DataGridView1.Columns.Count - 1
If k = DataGridView1.Columns.Count - 1 Then ' last column dont put , separate
Headerline = Headerline & DataGridView1.Columns(k).HeaderText
Else
Headerline = Headerline & DataGridView1.Columns(k).HeaderText & ","
End If
Next
file.WriteLine(Headerline) ' this will write header names at the first line
' collect the data
For i = 0 To DataGridView1.Rows.Count - 1
Dim DataRow As String
For k = 0 To DataGridView1.Columns.Count - 1
If k = DataGridView1.Columns.Count - 1 Then
DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value ' last column dont put , separate
End If
DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value & ","
Next
file.WriteLine(DataRow)
DataRow = ""
Next
loopend:
file.Close()
End Sub