export SQL data to a csv file from ASP.net - sql

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

Related

Append multiple CharW code in Ms word VBA

I want to replace some characters into Unicode character in ms word.
So, I have this string: 2437,2478,2479. I would like to convert this into CharW(2437) & CharW(2478) & CharW(2479)
I tried to split it with an array and want to achieve my goal by the following code:
SplitChar = "2437,2478,2479"
Dim test
SplitChar2 = Split(SplitChar, ",")
For j = 0 To UBound(SplitChar2)
' What I Actually need to do here for appending in `test`
Next
When I will call test it should be returned CharW(2437) & CharW(2478) & CharW(2479)
Is it possible by ms word VBA?
Thanks.

Duplicate row in a table after insert

I have a block of code that imports data from a text file to a table in Access. Each row in the text file should be saved separately in the table, but sometimes I have a duplicate row in the table. For example I have a text file like this:
Water
Bird
Summer
Sometimes and NOT always I see two Summer in the table. Always the last row of the text file is duplicated.
here is my VB code:
Private Sub Command11_Click()
Dim ifile As Integer
Dim db As Database
Dim name As String
Let ifile = FreeFile
name = util1.fDateiName("*.lab", "Lable")
Me.RecordSource = ""
DoCmd.RunSQL ("DELETE * FROM tb_lable_Daten")
Me.RecordSource = "SELECT name FROM tb_lable_Daten"
If name <> "" Then
Open name For Input As ifile
While Not EOF(ifile)
Line Input #ifile, entireline
'MsgBox entireline
DoCmd.RunSQL ("INSERT INTO tb_lable_Daten (name) VALUES ('" & entireline & "');")
Wend
List5.Requery
List5.SetFocus
MsgBox ("Die Daten sind erfolgreich gespeichert")
End If
End Sub
How can I solve this problem? and why does this problem occur?
In my view it seems somehow the file is processing beyond the last
line (which is summer in this case). Since you are not initializing
the varaible i:e entireline during each iteration so for the messed up
case its taking the last valid input (summer in your case). Try to
check and insert if and only if you have a valid value in entireline
variable and then re-initialize the entireline variable to blank after insertion. I hope this will solve the issue.

Split text File into Access DB using 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

Enumerate 'columns' in Entity Framework

we are dipping our toes with EF4 and have hit a wall.
We have an application that manages member data and a core requirement is to generate letters using Word mail merge.
In the current implementation we generate a dataset for the required records and enumerate it's columns and rows to create a tab delimited text file that Word can use to merge from. (This works really well, the Tab is used as there are multi-line results in the file such as FormattedAddressBlock).
With EF4 there is no way to convert internally to a dataset (this feature was dropped after the Orcas beta), so to the question:
How do we enumerate the columns and rows of a LINQ or ObjectQuery to allow us to build the text file.
Here is a sample of code we use with the datatable.
Using wmTextWriter As TextWriter = New StreamWriter(WordMergeDataFile)
' Write the header row to the merge data file.
Dim wmOutput As New StringBuilder()
For i As Integer = 0 To MergeData.Columns.Count - 1
wmOutput.Append(MergeData.Columns(i).ColumnName & vbTab)
Next
wmOutput.Remove(wmOutput.Length - 1, 1) ' Remove the trailing Tab character.
wmTextWriter.WriteLine(wmOutput.ToString)
' Loop through the datatable and write out the data rows to the work merge file.
wmOutput = New StringBuilder()
With MergeData
For iRowNo As Integer = 0 To .Rows.Count - 1
For iColNo As Integer = 0 To .Columns.Count - 1
wmOutput.Append(DOUBLEQUOTE & .Rows(iRowNo).Item(iColNo).ToString & DOUBLEQUOTE & vbTab)
Next
wmOutput.Remove(wmOutput.Length - 1, 1) ' Remove the trailing Tab character.
wmTextWriter.WriteLine(wmOutput.ToString)
wmOutput = New StringBuilder()
Next
End With
wmOutput = Nothing
wmTextWriter.Close()
End Using
Any help would be much appreciated.
Mark Harby
Nottingham. UK

EDIFACT How to group, spilt, sort and sum up values from a EDI string into variables in VB.NET

I am new to VB.Net 2008. I have a tricky task to resolve, it is regarding extracting characters (values) from a long string, the extracted values from the text shall be summed up and sorted by keywords, reformatted and saved into a CSV file.
It looks something like this but much longer :
UNH+RAM6957'COMPANY1BY500C10'ZEW+REQEST6957'COMPANY2SL200C20'COMPANY1SL300C10'ZEW
The values are seperated by ' .
As first step I splitted the string to make it readable, I used the function like:
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = p_EDI
aryTextFile = LineOfText.Split("'")
For i = 0 To UBound(aryTextFile)
Console.WriteLine((aryTextFile(i)))
Next i
Now the result looks like:
UNB+UNOA:1+CCP:ZEW+STE:ZEW+100901:1200+2010917283
UNH+M000001+ORDRSP:D:96A:UN:EGT102
BGM+02G::ZEW+NOMRES24364+34
DTM+Z05:0:805
DTM+137:201009011000:203
DTM+Z01:201009090400201009100400:719
RFF+AHI:GSCOMPANY1
NAD+ZSO+CCP::ZEW
NAD+ZSH+GSSTATKRAFT::ZEW
TDT+41G++70
LOC+Z11+:::TTF
LIN+1+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBNP::ZEW
LIN+2+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBPA::ZEW
So far so good:
Now I have to extract the date and time from the header:
The line looks like:
**DTM+137**:201009011000:203 should look like
DTM+137:2010.09.01-10:00:203 and store it into a 'incomming_DTM' variable for example
Now the message period would be interresting to know:
The line looke like:
**DTM+Z01**:201009090400201009100400:719 the output should look like:
DTM+Z01 2010.09.09-04:00, 2010.09.10-04:00 and store it into 'period_DTM' variable
As next step I need to parse the next lines until it reaches the KEYWORD LIN
Like:
LIN+1+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBNP::ZEW
NAD+ZSH+COMPANY1RPH N001::ZEW (P Character in word -> SELL QTY:0 KW/h)
LIN+2+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBPA::ZEW
NAD+ZSH+COMPANY1RRH N001::ZEW (R Character in word -> BUY QTY:0 KW/h)
and store the KEYWORDS "QTY" "DTM" "NAD+ZSH" and its following Characters
into variables.
THEN I need to parse until it reaches the next LIN Keyword and store the
keywords there into vaiables again. The goal of this complicated exercise is,
to sum up values of QTY and NAD+ZSH+COMPANY1RVH and NAD+ZSH+COMPANY1RPH
If we have a closer look at the last zwo charaters in COMPANY1RRH and COMPANY1RPH
we see RH and PH, RH means buy and PH means sell.
Maybe it is possible to store BUY or SELL into a Contract vaiable for each LIN?
I need to sum up all sells and buys which where found in the string.
Every LIN marks a time period of one hour, so we have probably 24 series per
string which contains 24 LIN every LIN have a Time period, BUY or SELL keywords
and a Quantity.
Can someone please help me with this task?
As first step, storing the keywords and its follwoing characters into variables would
be a very good start. It might be very good to do that probably until the parser reaches the LIN, then store the found values into a CSV file or Array?, then parse until the next LIN and so on...
I would like to create a CSV file out of the results like: So the CSV should contain
24 records one per every hour per every LIN..
Dim csvData = Now & "," & "TRADED_QTY" & "," & DTM+Z01 & "," & "N" & "," & QTY & "," & "KWH/h" & "," & Contract
Console.WriteLine(csvData)
Creating the CSV File with True Flag -> Append data to CSV.
Dim csvFile As String = "C:\Test.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
Any ideas are highly welcome, I consider this as very complex task
espacial as I am really new to VB.NET.
Thank you in advance!
I see "EDI" in your code. If this is an EDI format, then you should have, or be able to get, some kind of EDI specification. Likely, it will be a fixed-length specification, meaning that "Value X is characters 1 to 9", "Value Y is characters 10 to 11", "Value Z is character 12", etc.
Here is one possible approach to parse out the KEYWORDS as first step:
Dim EDI As Object
EDI = dataReader(0)
'Convert EDI Object into a string and write it to the console.
Dim p_EDI As String = Convert.ToString(EDI)
'Create LineBreaks after every " ' "
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = p_EDI
aryTextFile = LineOfText.Split("'")
'Starting with IF clause to find keywords
For Each line As String In aryTextFile
Console.WriteLine(line)
If line.StartsWith("UNB") Then
Dim foundUNB_Data = p_EDI.IndexOf("UNB")
'Start at that position and extract UNB + 27 characters
Dim UNBData = EDI.Substring(foundUNB_Data, 30)
Console.WriteLine(UNBData)
ElseIf line.StartsWith("LIN") Then
.
.
ElseIf line.StartsWith("QTY") Then
.
.
End If
Next
Any further ideas are highly welcome..
Thank you.