Split text File into Access DB using SQL - sql

All,
This is an example of three lines in my text File NEW_SCANNING.txt:
I;05/29/2013;06:55:37;3124480071200;1;801;1;;1
I;05/29/2013;06:56:05;0049004004827;1;801;1;;1
I;05/29/2013;06:56:09;54491069;1;801;1;;1
I want to be able to select what's between the 3rd and 4th " ; ", in this case it would be
3124480071200
0049004004827
54491069
So what I need the program to do is to search every line that starts with the letter I and select what's between the 3rd and 4th ;.
Then it has to put the first selection in a combobox named SelBarc. If it has done this for the first, it has to move on to the second and so on and so on ...
Anyone who can help me?

Open, read, split to lines then loop;
dim lines() as string,i as long
Open "c:\xxx\NEW_SCANNING.txt" for input as #1
lines = split(Input$(lof(1), #1), vbcrlf)
close #1
For i = 0 to ubound(lines)
if Left$(lines(i), 1) = "I" then combobox.additem split(lines(i), ";")(3)
Next

Related

Display in column line number

Dim files = From file In Directory.EnumerateFiles(txtFolder.Text, txtType.Text, SearchOption.AllDirectories)
From line In System.IO.File.ReadLines(file) Where line.Contains(txtFindWhat.Text) Select New With {file, line}
For Each f In files
Dim item As New ListViewItem($"{f.file}") 'First Column File Localtion
item.SubItems.Add($"{f}") 'Second Column Add The line number where found the text
item.SubItems.Add($"{f.line}") 'Third Column Text Search
ListView1.Items.Add(item) 'Add Records
Next
Question::
How to display the line number where it was found in the file in the second column?
Example: Test.txt contains:
asdasd
Testa
Geter
Better
So I search for text "Better" and display in Column 2 that it was found at line 4 in file.
I think you tried to do too much in a single line. I broke it down into two steps. Remember Linq is doing the loops behind the scenes so it really shouldn't slow down your code.
What will slow down your code is updating the user interface in a loop. I accumulated the ListViewItems in a list and then added them all at once after the loop.
The line number was determined by adding a line counter. It is incremented inside the inner loop and reset to 1 for each file in the outer loop. Since humans start counting at 1 that is what I used rather than the computer's counting system that starts with 0.
Private Sub OPCode()
Dim files = Directory.EnumerateFiles(txtFolder.Text, txtType.Text, SearchOption.AllDirectories)
Dim lst As New List(Of ListViewItem)
For Each f In files
Dim lineNumber As Integer = 1
Dim lines = File.ReadAllLines(f)
For Each line In lines
If line.Contains(txtFindWhat.Text) Then
Dim li As New ListViewItem(f)
li.SubItems.Add(lineNumber.ToString)
li.SubItems.Add(line)
lst.Add(li)
End If
lineNumber += 1
Next
Next
ListView1.Items.AddRange(lst.ToArray)
End Sub

How can I remove rows starting with ' in a variant?

Following the answer to this question, I execute different queries stored in a .txt file using the following code:
Dim vSql As Variant
Dim vSqls As Variant
Dim strSql As String
Dim intF As Integer
intF = FreeFile()
Open "MyFile.txt" For Input As #intF
strSql = Input(LOF(intF), #intF)
Close intF
vSql = Split(strSql, ";")
On Error Resume Next
For Each vSqls In vSql
DoCmd.RunSQL vSqls
Next
The queries are separated by ;, and each query is preceded by a comment line, starting with ' and ending with ;(so that it gets split by vSql = Split(strSql, ";") ).
The resulting vSql variant is composed of valid SQL statements, interspersed with comment lines starting with '. The current code works, but I would like to remove the On Error Resume Next so that a faulty SQL statement returns an error instead of being ignored.
How can I remove the rows starting with ' in the variant before executing the For Each loop? Or is there another way to accomplish my goal? The comment character can be changed if necessary.
Alternatively, this should do it to:
For Each vSqls In vSql
If Not CStr(vSqls) Like "'*" Then DoCmd.RunSQL vSqls
Next
It depends on exactly how the file is stored, but the simplest way is to find the first return character and take the rest of the text.
vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCrLf) + 2)
or
vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCr) + 1)
Bear in mind that this will only remove the first line so if there are blanks you will need to check whether the next line starts with a '.
And you might find that your queries don't work if they are spread across more than one line that you might need to deal with that by replacing any remaining carriage returns with a space.

export SQL data to a csv file from ASP.net

I have a view in the database, i would like to call that view and export the data to a Csv file. I have used the following link to come up with a solution however my view returns a few columns which has values with commas so while opening the csv i get the error the csv is unsafe, might by a sylk file etc. Once i open it there is no date in the CSV.
The link i used
https://www.aspsnippets.com/Articles/Export-data-from-SQL-Server-to-CSV-file-in-ASPNet-using-C-and-VBNet.aspx
I am using VS 2017
SQL and
VB.Net
Thanks in advance
That code is a bit dodgy actually, because it is explicitly replacing commas in data with semicolons and it is also adding an extra comma to the end of each line. Here's concise way to generate CSV data from a DataTable with quoted field values:
Dim csv = String.Join(Environment.NewLine,
myDataTable.AsEnumerable().
Select(Function(row) """" &
String.Join(""",""",
row.ItemArray) &
""""))
If you're not au fait with LINQ, here's a more conventional way to do the same thing:
Dim csv As String
For rowIndex = 0 To myDataTable.Rows.Count - 1
'Add a line break before all but the first line.
If rowIndex > 0 Then
csv &= Environment.NewLine
End If
Dim row = myDataTable.Rows(rowIndex)
'Add a double-quote before the first field value.
csv &= """"
For columnIndex = 0 To myDataTable.Columns.Count - 1
'Add a closing double-quote, a delimiting comma and an opening
' Double-quote before all but the first field value.
If columnIndex > 0 Then
csv &= ""","""
End If
csv &= row(columnIndex).ToString()
Next
'Add a double-quote after the last field value.
csv &= """"
Next

How vb.net split string

I have a file txt file that values i want split after value "accession_number=" and before value "&token"
example Values in text file :
10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=5049885&study_uid=201702060824&accession_number=20170206082802&token
10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=4409276&study_uid=201702060826&accession_number=20170206083002&token
10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=4402764&study_uid=201702060801&accession_number=20170206080416&token
10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=4402537&study_uid=201702060837&accession_number=20170206084025&token
example values after proccess :
20170206082802
20170206083002
20170206080416
20170206084025
Thank you
You can read each line into an array of strings using File.ReadAllLines() and then iterate over that and parse the information using a Regex.
'Declare the Regex.
Dim Parser As New Regex("(?<=accession_number\=)\d+", RegexOptions.IgnoreCase)
'Read the file's lines into an array of strings.
Dim Lines As String() = File.ReadAllLines("C:\test.txt")
'Iterate over the array.
For Each Line As String In Lines
Dim m As Match = Parser.Match(Line) 'Match the pattern.
If m.Success = True Then 'Was the match successful?
Console.WriteLine(m.Value) 'Print the matched value.
End If
Next
Online test: http://ideone.com/VU5Iyj
Regex pattern explanation:
(?<=accession_number\=)\d+
(?<= => Match must be preceded by...
accession_number\= => ..."accession_number=".
) => End of preceding capture group.
\d+ => Match one or more numerical characters.
You can do it by reading all lines, and then based on the lines you can execute following code (assuming the file you want to read is located at C:\test.txt)
dim results = from line in File.ReadAllLines("C:\test.txt") _
where not String.IsNullOrWhiteSpace(line) _
from field in line.Split("&") _
where field.StartsWith("accession_number=") _
select field.Split("=")(1)
for each result in results
Console.WriteLine(result)
next
This will use as an input all lines, and then for the lines that are not empty, it will split using & and then it checks if that field startswith the accession_number, if it does, it splits by = to return the second item in the array.
As an extra explanation:
from line in File.ReadAllLines("C:\test.txt")
while evaluate every single line in the file
' input eg: 10.0.0.6:80/ImageSuite/Web/Worklist/DICOMViewer.aspx?patient_id=5049885&study_uid=201702060824&accession_number=20170206082802&token
where not String.IsNullOrWhiteSpace( line )
will exclude all empty lines (or lines that exist only of whitespaces)
from field in line.Split("&")
will split every found line into an array of strings using the & as a separator
' field eg: accession_number=20170206082802
where field.StartsWith("accession_number=")
will exclude all fields that do not start with accession_number=
select field.Split("=")(1)
' result sample: 20170206082802
will return for any matches the part after =
A full example you can find on this dotnetfiddle. It uses a slightly different method to read from stream, simply because in that environment, I cannot provide a dummy file, however, it should do the trick

Copying a specfic line within a cell into another cell

I have a spreadsheet that has multiple lines within a cell, all with line breaks.
e.g.
Name: a
Age: 1
University: 1
Degree: 3
Year: 3
I am looking to extract (in this example) the University infomation that is contained within the cell and copy it into another cell in another column.
There are about 1000 records in my document so to copy and paste by hand will be time consuming.
Any help will be appreciated
Cheers
Joe
You could do this with an Excel formula.
Assuming your data is in column A, and you want the extraction in column B, and assuming you put a title in row 1, you could do as in the following image:
(Note that I have a semi-colon in the formula as list separator, use comma instead)
The formula in B2 is:
=MID($A2, FIND(B$1, $A2) + LEN(B$1),
FIND(CHAR(10), $A2 & CHAR(10), FIND(B$1, $A2)) - FIND(B$1, $A2) - LEN(B$1))
The formula has some duplication; here are some of the parts explained:
FIND(B$1, $A2) returns the position of the title in the text
FIND(B$1, $A2) + LEN(B$1) returns the position of what follows that title in the text
FIND(CHAR(10), $A2 & CHAR(10), FIND(B$1, $A2)) returns the position of a newline character following the title, making sure that if none is present, a position beyond the string length is returned
As long as you put the column titles to whatever sub-string you are looking for, you can copy/drag the same formula to other columns and rows.
If there is a single break between each line, then in B1 enter:
=TRIM(MID(SUBSTITUTE($A1,CHAR(10),REPT(" ",999)),COLUMNS($A:C)*999-998,999))
This assumes that:
the university line is the third line
you want the entire line
I'm providing an answer even though you haven't provided what attempts you've made so far, which is how questions on this site usually work...but today I'm feeling generous :)
Use a combination of MID and FIND formulas, like the following:
=MID(A1,FIND("University",A1),FIND("Degree",A1)-FIND("University",A1)-2)
I put your example text in Cell A1 for my test, and it returned University: 1. This however will only work if University is always followed by Degree in the text strings.
The other method would be to replace the last part of your MID statement (the part asking for length to return) with the exact number of characters to return, which in this case would be 13, like the following:
=MID(A1,FIND("University",A1),13)
This assumes that the integer associated with University is always 1 character in length.
Either way, a combination of the above two formulas should get you what you need. VBA should not be necessary in this case.
Lines in a cell value are separated by the line feed character vbLf, so to extract the information out of the cell value you can use String-Functions Mid(...) and InStr(...):
Dim cellValue as String
Dim extracedValue as String
Dim keyWord as String
Dim posStart as Integer, posEnd as Integer
extractedValue = "" ' Not necessary, but I prefer initialized variables
cellValue = ActiveSheet.Cells(1,1).Value ' Put your cell here
keyWord = "University" ' Put your keyword here
posStart = InStr(1, cellValue, keyWord) ' Find keyword in the string
If (posStart > 0) Then
posEnd = InStr(posStart, cellValue, vbLf) ' Find next line feed after the keyword
If (posEnd > 0) Then
extractedValue = Mid(cellValue, posStart, posEnd - posStart) ' Extract the value
End If
End If
I haven't tested the code, but you should get the idea.