How can I export the datagridview to .csv without headers? - vb.net

My csv file is like this
There is no blank spaces or whatsoever.
The problem as you can see is that I do not know how to export my datagridview as .csv excluding column headers.
This is how I have done my export code:
Private Sub IncomeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles IncomeToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "CSV|*.csv"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim incomefile As String = String.Empty
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
For Each row As DataGridViewRow In Expense.Rows
For Each cell As DataGridViewCell In row.Cells
incomefile = incomefile & cell.FormattedValue.replace(",", "") & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
Next
System.IO.File.WriteAllText(saveFileDialog1.FileName, incomefile)
End If
Dim msg1 = "Export Successful"
Dim title = "Excel Export"
MsgBox(msg1, , title)
End Sub
Please advise me. Some others mentioned that I'd better off use datatable to export it, but since I started to learn computer programming 43 hours ago, I have no clue on how to declare the data i have put in my datagridview and export it as csv file.

Remove those lines
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next

Give this a try.
Private Sub BtnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExport.Click
SFD.InitialDirectory = "C:\"
SFD.Title = "Save Your File"
SFD.Filter = "Microsoft Excel(*.xls)|*.xls|Comma Delimited File(*.csv)|*.Csv"
SFD.OverwritePrompt = True
SFD.ShowDialog()
strFileName = SFD.FileName
' If SFD.ShowDialog() = DialogResult.OK Then
If SFD.FilterIndex = 1 Then
Call export()
Else
Call csv()
End If
' End If
End Sub
Also, try it this way.
Dim numCols As DataGridViewCell
Dim sw As New System.IO.StreamWriter("d:\\output.txt")
For Each numRows As DataGridViewRow In DataGridView1.Rows
Dim intCellCount As Integer = numRows .Cells.Count
Dim intCounter As Integer = 1
For Each numCols In numRows .Cells()
If intCounter <> intCellCount Then
sw.Write(numCols .Value.ToString & ",")
Else
sw.WriteLine(numCols .Value.ToString)
End If
intCounter += 1
Next
Next

Related

How to move DataGridView row to another DataGridView in another form, with CSV Datasource- VB.net

Im using a CSV to load data and save data from the DataGridView I have in a form. I would now like it so with a button click event I can send a row checked via the checkbox column on the DataGridView, to another dataGridView which is hosted in another form.
If it helps, here is the load im using to load and save the DataGridView contents.
Private Sub btnLoadDGVGeneral_Click(sender As Object, e As EventArgs) Handles btnLoadDGVGeneral.Click
' PURPOSE: Load CSV file containing tasks into DataGridView
' Clearing DGV Rows allows for Tasks to not double up when rebooting the program
dataGVGeneral.Rows.Clear()
'New Variable: fname, represents File Path of CSV as String
Dim fname As String = "E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv"
Dim reader As New StreamReader(fname, Encoding.Default)
Dim sline As String = ""
Dim colsexpected As Integer = 7
Dim r As Integer = 0
'StreamReader will the file Line by Line, and add it to the variable sline
'First sline statement is Out of Loop, as first line of CSV contains headings to what each figure represents in a line.
sline = reader.ReadLine
Do
'Now sline will read the 2nd line and so forth
sline = reader.ReadLine
'If no value is found on that line of the CSV file (at the end), then the loop will exit
If sline Is Nothing Then Exit Do
'Details is as a variable, which when called upon, places each value into different columns for that row
Dim details() As String = sline.Split(",")
dataGVGeneral.Rows.Add()
For i As Integer = 0 To 6
dataGVGeneral.Rows(r).Cells(i).Value = details(i)
Next
'Increments value of "r" by 1, meaning next line of CSV will be added to the next row.
Dim v As Integer = r + 1
r = v
Loop
reader.Close()
End Sub
Private Sub btnSaveGeneralDGV_Click(sender As Object, e As EventArgs) Handles btnSaveGeneralDGV.Click
Dim StrExport As String = ""
For Each C As DataGridViewColumn In dataGVGeneral.Columns
StrExport &= """" & C.HeaderText & ""","
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
For Each R As DataGridViewRow In dataGVGeneral.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= """" & C.Value.ToString & ""","
Else
StrExport &= """" & "" & ""","
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next
Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv", False)
tw.Write(StrExport)
tw.Close()
End Sub

how to send the output to a logfile and richtextbox

I have the follow code that works for sending the output to a richtextbox. I cant figure out how to also have the output sent to a log file if I choose as well. this is the beginnings of my code for choosing to log the output. I cant figure out how to get it to log the output to the file location.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If (OpenFileDialog1.ShowDialog() = DialogResult.OK) Then
TextBox31.Text = Chr(34) & OpenFileDialog1.FileName & Chr(34)
End If
End Sub
here is my working code for displaying the output in the richtextbox.
Private Sub ExecuteButton_Click(sender As Object, e As EventArgs) Handles ExecuteButton.Click
System.Windows.Forms.Application.DoEvents()
Dim myprocess As New Process
Dim startinfo As New ProcessStartInfo(TextBox3.Text, TextBox1.Text) With {
.UseShellExecute = False,
.RedirectStandardOutput = True,
.CreateNoWindow = True
}
myprocess.StartInfo = startinfo
myprocess.Start()
Dim str1 As String = ""
Using MyStreamReader As IO.StreamReader = myprocess.StandardOutput
str1 &= MyStreamReader.ReadToEnd
End Using
RichTextBox1.Text = str1
End Sub
Note: This is what I used to be able to log the output
If CheckBox34.Checked = True Then
Dim objWriter As New System.IO.StreamWriter(TextBox31.Text & "\" & Format(Now, "dd-MMM-yyyy") & ".log", True)
objWriter.WriteLine(Format(Now, "dd-MMM-yyyy HH:mm:ss ") & TextBox4.Text & vbCrLf & str1)
objWriter.Close()
End If
Try With this sample:
Dim MyPath = "C:\MyLog.Log"
FileOpen(1, MyPath, OpenMode.Append)
Dim lNumberofRecs = LOF(1)
Print(1, Format(Now, "dd-MMM-yyyy HH:mm:ss") & "#Import Begin" & vbCrLf)
FileClose(1)
or with this:
Dim objWriter As New System.IO.StreamWriter("C:\MyData\mylog.log", True)
objWriter.WriteLine("each log data you have")
objWriter.Close()

File can't be accessed because it's already in use

I have a Sub that reads a file that was created in another Sub. I'm getting an error
Can't access file in use in other process
From what I've read on the net I need to close the StreamReader. I've tried to use .close() on different variables, but nothing seems to work.
Below is the code that writes the file the other Sub then accesses.
Private Sub CreateGraphicsFunction(sender As Object, e As EventArgs)
Dim Regex = New Regex("infoEntityIdent=""(ICN.+?)[""].*?[>]")
strGraphicFile = MoveLocation & "\ICN-LIST.txt"
Dim ICNFiles = Directory.EnumerateFiles(MovePath, "*.*", SearchOption.AllDirectories)
For Each tFile In ICNFiles
Dim input = File.ReadAllText(tFile)
Dim match = Regex.Match(input)
If match.Success Then
output.Add(match.Groups(1).Value)
End If
Next
File.WriteAllLines(strGraphicFile, output)
locationGraphicsLog = strGraphicFile
End Sub
The other Sub that reads the file created
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Application.UseWaitCursor = True
Application.DoEvents()
Me.Refresh()
Dim sGraphicFilesToFind As String
Dim graphicLocation As String
'MoveWithPath As String
Dim graphicFile As String
graphicLocation = txtSearchICN.Text
MoveLocation = MovePath
graphicLogFile = MoveLocation & "\Reports\1-OrphanedFilesItems.txt"
Dim FILE_NAME As String
FILE_NAME = MoveLocation & "\ICN-LIST.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim sGraphicFile As String
Do While objReader.Peek() <> -1
graphicFile = objReader.ReadLine()
sGraphicFilesToFind = graphicLocation & "\" & graphicFile & "*.*"
sGraphicFile = graphicFile
Dim createGraphicReportFldr As String
Dim paths() As String = IO.Directory.GetFiles(graphicLocation, sGraphicFile, IO.SearchOption.AllDirectories)
If paths.Count = 0 Then
'Debug.Print(graphicFile)
If System.IO.File.Exists(graphicLogFile) = True Then
Dim objWriter As New System.IO.StreamWriter(graphicLogFile, IO.FileMode.Append)
objWriter.WriteLine(graphicFile)
objWriter.Close()
Else
'MsgBox("Creating Orphaned graphicFile Now. ")
createGraphicReportFldr = MoveLocation & "\Reports"
If Not IO.Directory.Exists(createGraphicReportFldr) Then
IO.Directory.CreateDirectory(createGraphicReportFldr)
'MsgBox("folder created" & createGraphicReportFldr)
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(graphicLogFile)
writeFile.Write(graphicFile & vbCrLf)
writeFile.Close()
Else
'MsgBox("Folder already exist")
End If
End If
Else
For Each pathAndFileName As String In paths
Dim createGraphicsFolder As String
'Dim moveFileToNewFolder As String
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast As String = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toGraphiicFileLocation As String
'MsgBox("sRegLast " & sRegLast)
fileGraphicLoc = MoveLocation & sRegLast
createGraphicsFolder = MoveLocation & "\Figures"
moveGraphicFileToNewFolder = MoveLocation & "\Figures\" & sRegLast
toGraphiicFileLocation = createGraphicsFolder & "\" & sRegLast
'MsgBox("FileLoc " & fileLoc)
If Not IO.Directory.Exists(createGraphicsFolder) Then
IO.Directory.CreateDirectory(createGraphicsFolder)
' MsgBox("folder created" & createGraphicsFolder)
End If
If System.IO.File.Exists(fileGraphicLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveGraphicFileToNewFolder)
Debug.Write("Graphics moved to : " & moveGraphicFileToNewFolder & vbCrLf)
End If
End If
Next
End If
Loop
'MsgBox("graphicFiles have been moved")
Call CreateGraphicsFunction(Nothing, System.EventArgs.Empty)
Application.UseWaitCursor = False
Application.DoEvents()
' Me.Close()
End Sub
In the "other Sub", change
Dim objReader As New System.IO.StreamReader(FILE_NAME)
to
Using objReader = New System.IO.StreamReader(FILE_NAME)
and add End Using where you are done with it. Probably right after Loop. This will ensure that the disposable stream is always disposed.
See Using Statement (Visual Basic). You almost always want to wrap an IDisposable object in a Using block if you are able to restrict its scope to a single method.

Splitting Word document into multiple .txt files using a macro

I am splitting a single MS Word document into multiple using a custom delimiter. I am able to create multiple files in MS Word format, but I want to create multiple .txt files instead.
The code that I am using now is:
Sub SplitNotes(delim As String, strFilename As String)
Dim doc As Document
Dim arrNotes
Dim I As Long
Dim X As Long
Dim Response As Integer
arrNotes = Split(ActiveDocument.Range, delim)
Response = MsgBox("This will split the document into " &
UBound(arrNotes) + 1 & " sections. Do you wish to proceed?", 4)
If Response = 7 Then Exit Sub
For I = LBound(arrNotes) To UBound(arrNotes)
If Trim(arrNotes(I)) <> "" Then
X = X + 1
Set doc = Documents.Add
doc.Range = arrNotes(I)
doc.SaveAs ThisDocument.Path & "\" & strFilename & Format(X, "000")
doc.Close True
End If
Next I
End Sub
Sub test()
' delimiter & filename
SplitNotes "%%%%%%%%%%%%%%", "Notes "
End Sub
Can anyone help me with this please?
Try this and see if it does what you want.
Sub SplitNotes(delim As String, strFilename As String)
Dim doc As Document
Dim arrNotes
Dim I As Long
Dim X As Long
Dim Response As Integer
arrNotes = Split(ActiveDocument.Range, delim)
Response = MsgBox("This will split the document into " & UBound(arrNotes) + 1 & " sections. Do you wish to proceed?", 4)
If Response = 7 Then Exit Sub
For I = LBound(arrNotes) To UBound(arrNotes)
If Trim(arrNotes(I)) <> "" Then
X = X + 1
Set doc = Documents.Add
doc.Range = arrNotes(I)
doc.SaveAs ThisDocument.Path & "\" & strFilename & ".txt"
doc.Close True
End If
Next I
End Sub
Sub test()
' delimiter & filename
SplitNotes "///", "Notes "
End Sub

Only column text appears when csv file is imported to datagridview vb.net

This is my first vb.net program, so please bear with me if my question is very mediocre.
Before mentioning my problem, the mechanism of my accounting program is that if the user would input data into the datagridview and export it, so that when he restarts the program, he can import the exported data.
I have imported this .csv file to my datagridview
The problem is that when I have imported it, only column texts would appear like this.
This is the export code that I have used to create the .csv file.
Private Sub ExportToExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportToExcelToolStripMenuItem.Click
Dim msg1 = "Export Successful"
Dim title = "Excel Export"
MsgBox(msg1, , title)
Try
Dim iexport1 As String = ""
Dim eexport1 As String = ""
For Each C As DataGridViewColumn In Income.Columns
iexport1 &= """" & C.HeaderText & ""","
Next
iexport1 = iexport1.Substring(0, iexport1.Length - 1)
iexport1 &= Environment.NewLine
For Each R As DataGridViewRow In Income.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
iexport1 &= """" & C.Value.ToString & ""","
Else
iexport1 &= """" & "" & ""","
End If
Next
iexport1 = iexport1.Substring(0, iexport1.Length - 1)
iexport1 &= Environment.NewLine
Next
For Each C As DataGridViewColumn In Expense.Columns
eexport1 &= """" & C.HeaderText & ""","
Next
eexport1 = eexport1.Substring(0, eexport1.Length - 1)
eexport1 &= Environment.NewLine
For Each R As DataGridViewRow In Expense.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
eexport1 &= """" & C.Value.ToString & ""","
Else
eexport1 &= """" & "" & ""","
End If
Next
eexport1 = eexport1.Substring(0, eexport1.Length - 1)
eexport1 &= Environment.NewLine
Next
Dim tw As IO.TextWriter = New IO.StreamWriter(path:="C:\Users\S2009516\Desktop\JanuaryIncome.CSV")
tw.Write(iexport1)
tw.Close()
Dim tw2 As IO.TextWriter = New IO.StreamWriter(path:="C:\Users\S2009516\Desktop\JanuaryExpense.CSV")
tw2.Write(eexport1)
tw2.Close()
Catch ex As Exception
End Try
End Sub
And this is the one I have used for importing csv file.
Private Sub ImportFromExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ImportFromExcelToolStripMenuItem.Click
Dim expenseload1 As String = "C:\Users\S2009516\Desktop\JanuaryExpense.CSV"
Dim incomeload1 As String = "C:\Users\S2009516\Desktop\JanuaryIncome.CSV"
Try
Dim expensereader1 As New StreamReader(expenseload1, Encoding.Default)
Dim incomereader1 As New StreamReader(incomeload1, Encoding.Default)
Dim eline As String = ""
Dim iline As String = ""
Do
eline = expensereader1.ReadLine
iline = incomereader1.ReadLine
If eline Is Nothing Then Exit Do
If iline Is Nothing Then Exit Do
Dim words() As String = eline.Split(",")
Dim words2() As String = iline.Split(",")
Income.Rows.Add("")
Expense.Rows.Add("")
For ix As Integer = 0 To 3
Me.Income.Rows(Income.Rows.Count - 1).Cells(ix).Value = words2(ix)
Me.Expense.Rows(Income.Rows.Count - 1).Cells(ix).Value = words(ix)
Next
Loop
expensereader1.Close()
incomereader1.Close()
Catch ex As Exception
End Try
End Sub
I have no clue on why this is happening... I have followed all the steps in the tutorial video.. Please save my soul... I have been stuck with this for 2 days already.