Export data to Excel file from SQL Server database - vb.net

I want to create a program that can export data from sql server database to
excel file and the file name must be auto generated and auto incremented.
I query data from server using date time picker as below:
`command.CommandText = ("Select * from ComponentCheckerSystem where
Last_Update between #FromDate AND #ToDate;")
command.Parameters.Add("#FromDate", SqlDbType.Date).Value =
DateTimePicker1.Value.Date
command.Parameters.Add("#ToDate", SqlDbType.Date).Value =
DateTimePicker2.Value.Dat`
'set final path
Dim fileName As String = "\Summary of Operator Scan Wrong Items"
+ ".xls" 'just set the file Name
Dim finalPath = f.SelectedPath + fileName
txtPath.Text = finalPath
oSheet.Columns.AutoFit()
Please help me to make a function to auto generate file name.
thank you.

To create a place in Settings for your data:
1.Project Menu > Properties (all the way at the bottom)
2. Choose the Settings tab (on the left)
3. File out the boxes Name: LastFile, Type: Integer, Scope: User Value: will be set for you to 0
Actually, you could store your LastFile variable value in a text file or a database but I chose App.config for convenience.
You already know how to set your directory and the following code will get you a new file name.
Private Function GetNewFileName() As String
Dim FileSuffix As Integer = My.Settings.LastFile
FileSuffix += 1
Dim NewFileName As String = String.Format("\Summary of Operator Scan Wrong Items{0}.xls", FileSuffix)
My.Settings.LastFile = FileSuffix
Return NewFileName
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim file As String = GetNewFileName()
Debug.Print(file)
End Sub

Related

How can I ignore a new line character when reading CSV file in VB.NET?

I wrote a utility in VB.NET that reads an input CSV file, does some processing (specifically it ignores the first 5 lines of the input file and replaces them with a header row saved in another file) and writes the information from the input file into a new output CSV file.
Where my program fails is when the input data includes new line characters within one column value within the CSV.
I would like to ignore the new line character within a CSV data row when I load it into my string array.
Here is my code (its embedded in a form)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim incsvPath = strFileName
Dim outcsvPath = fi.DirectoryName & "\" & outfilename
Dim headerPath = fi.DirectoryName & "\ACTIVITY_HISTORY_HEADER.csv"
Dim fileP As String = incsvPath
Dim fileheader As String = headerPath
Dim CSVheaderIn As New ArrayList
Dim CSVlinesIn As New ArrayList
Dim CSVout As New List(Of String)
CSVheaderIn.AddRange(IO.File.ReadAllLines(fileheader))
CSVlinesIn.AddRange(IO.File.ReadAllLines(fileP))
messageTB.AppendText(vbCrLf & vbCrLf)
For Each line As String In CSVheaderIn
Dim nameANDnumber As String() = line.Split(",")
messageTB.AppendText("csv file header row = " & line & vbCrLf & vbCrLf & "csv file contents follow ..." & vbCrLf)
CSVout.Add(line)
Next
Dim mySubAL As ArrayList = CSVlinesIn.GetRange(5, CSVlinesIn.Count - 5)
For Each line As String In mySubAL 'CSVlinesIn
messageTB.AppendText(line & vbCrLf)
CSVout.Add(line)
Next
IO.File.WriteAllLines(outcsvPath, CSVout.ToArray)
End Sub
This is fairly hard work actually; it'll be easier to use a library that knows how to read and write CSV with newlines in the data than roll your own - not saying you couldn't, but it's a wheel that has already been invented so why do it again?
I used Steve Hansen's Csv - right click your project in solution explorer, choose Manage Nuget Packages, click Browse, Search csv, install the right one
Imports System.Text
Imports Csv
Imports System.IO
Module Module1
Sub Main(args As String())
'open the headers file
Using hIn = File.OpenText("C:\temp\h.csv")
'setup instruction to the csv reader with headersabsent flag so we can get the first line as data
Dim hOptions = New CsvOptions With {.HeaderMode = HeaderMode.HeaderAbsent}
'take the first line into an array - these are our headers
Dim headers = CsvReader.Read(hIn, hOptions)(0).Values
'open the data file,
Using fIn = File.OpenText("C:\temp\a.csv")
'setup instruction for the reader to skip 5 rows, treat first row as data, and allow newlines in quoted fields
Dim fOptions = New CsvOptions With {.RowsToSkip = 5, .HeaderMode = HeaderMode.HeaderAbsent, .AllowNewLineInEnclosedFieldValues = True}
Using fOut = File.CreateText("C:\temp\a_out.csv")
'convert the ICsvLine rows in the reader to rows of String() that the writer will accept, and write them under the headers
CsvWriter.Write(fOut, headers, CsvReader.Read(fIn, fOptions).Select(Function(line) line.Values))
End Using
End Using
End Using
End Sub
End Module
You don't have to use this lib to read the headers; you could just file.ReadText().ReadLine().Split(","c) it
If you want to perform per-line processing on the elements, do this:
CsvWriter.Write(fOut, headers, CsvReader.Read(fIn, fOptions).Select(Function(line) ProcessLine(line.Values)))
...
Function ProcessLine(input As String()) As String()
'Note: If(input(8), "") returns input(8) unless it is nothing in which case "" is returned instead
If If(input(8), "").Length > 10 Then input(8) = input(8).Remove(10) 'Trim if over 10
If If(input(14), "").Length > 10 Then input(14) = input(14).Remove(10)
Return input 'Always return
End Function

VB.Net Search for text and replace with file content

This is a follow on question to a post I made. Append one file into another file
I need to search the master document for entities "&CH1.sgm" to "&CH33.sgm",
mark where they are in the master document and replace the entity call with the matching file "Chapter1.sgm" found in "fnFiles". I can change the file names and entities to anything if that will help.
My code copies the text of a file and appends it to the bottom of the master_document.sgm. But now I need it to be more intelligent. Search the Master document for entity markers, then replace that entity marker with that file contents match. The file number and entity number match up. e.g.(&CH1; and Bld1_Ch1.sgm)
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
Dim searchDir As String = txtSGMFile.Text 'Input field from form
Dim masterFile = "Bld1_Master_Document.sgm"
Dim existingFileMaster = Path.Combine(searchDir, masterFile)
'Read all lines of the Master Document
Dim strMasterDoc = File.ReadAllText(existingFileMaster) '// add each line as String Array.
'?search strMasterDoc for entities &Ch1.sgm
'?replace entity name "&Ch1.sgm" with content of file "Bld1_Ch1.sgm" this content if found below
'? do I use a book mark? Replace function?
'Get all the sgm files in the directory specified
Dim fndFiles = Directory.GetFiles(searchDir, "*.sgm")
'Set up the regular expression you will make as the condition for the file
Dim rx = New Regex(".*_Ch\d\.sgm")
Dim ch1 = New Regex(".*_Ch[1]\.sgm")
'Use path.combine for concatenatin directory together
'Loop through each file found by the REGEX
For Each fileNo In fndFiles
If rx.IsMatch(fileNo) Then
If ch1.IsMatch(fileNo) Then
Dim result = Path.GetFileName(fileNo)
'Use path.combine for concatenatin directory together
Dim fileToCopy = Path.Combine(searchDir, result)
'This is the file we want to copy into MasterBuild but at specific location.
'match &ch1.sgm inside strMasterDoc
Dim fileContent = File.ReadAllText(fileToCopy)
'Search master file for entity match then append all content of fileContent
File.AppendAllText(existingFileMaster, fileContent)
MessageBox.Show("File Copied")
End If
End If
Next
Close()
End Sub
If I understand correctly (big if), you want to replace the the text of the abbreviated chapter name in the master file with the contents of the file it refers to at the spot where the abbreviation is found.
I made a class to handle the details.
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
'Add a FolderBrowseDialog to your form designer
FolderBrowserDialog1.ShowDialog()
Dim searchDir As String = FolderBrowserDialog1.SelectedPath
Dim existingFileMaster = Path.Combine(searchDir, "Bld1_Master_Document.sgm")
Dim lstFileChanges = CreateList(searchDir)
'The following method does NOT return an array of lines
Dim strMasterDoc = File.ReadAllText(existingFileMaster)
For Each fc In lstFileChanges
strMasterDoc = strMasterDoc.Replace(fc.OldString, fc.NewString)
Next
File.WriteAllText(existingFileMaster, strMasterDoc)
End Sub
Private Function CreateList(selectedPath As String) As List(Of FileChanges)
Dim lstFC As New List(Of FileChanges)
For i = 1 To lstFC.Count
Dim fc As New FileChanges
fc.OldString = $"&CH{i}.sgm"
fc.FileName = $"Chapter{i}.sgm"
fc.NewString = File.ReadAllText(Path.Combine(selectedPath, fc.FileName))
lstFC.Add(fc)
Next
Return lstFC
End Function
Public Class FileChanges
Public Property OldString As String '&CH1.sgm
Public Property FileName As String 'Chapter1.sgm
Public Property NewString As String 'Contents of Chapter1.sgm, the string to insert
End Class
Testing .Replace
Dim s As String = "The quick brown fox jumped over the lazy dogs."
s = s.Replace("fox", "foxes")
MessageBox.Show(s)

VB.NET Writing MSSQL data to DBF format

I am trying to export MS-SQL data to DBF format.
Is there anyway to achieve this as I can't find any solution to this?
I am using SQL Server 2008 Express R2 in Visual Studio 2008.
Thanks in advance!
Try this link:
https://www.pcreview.co.uk/threads/export-data-from-mssql-to-dbf-using-vb-net.1239926/
Hi,
This is not as easy as you might suppose. I do it frequently, but I first
have to create the structure of the .dbf table I want to generate and then I
place it with an _ in the name in a designated subdirectory. The reason I
have to do this is because the odbc driver for ado .net is limited in the
datatypes it will create, so I can't very well fashion the .dbf file
directly inside .net.
The function below does the rest - it turns a given dataset into a .dbf
file, as you are trying to do; I simply pass the dataset, the .dbf name and
the number of columns to it.
Public Function tabletodbf(ByVal mtable As DataSet, ByRef mdbf As String, ByVal numcols As Integer) As Integer
' suppositions: the dbf file is in f:\imcapps\dbffiles; also, there is
' an empty of it with a _ at the end of the filename; also, we are working
' with dbf files exclusively in f:\imcapps\dbffiles; also, the table and
' the dbf have to have the exact same structure and in the same column #
' sequence; also, if the _ causes
' the file name to be too large, this probably won't work, so I have to
' ensure this doesn't happen
' signature:
' dim funcs as new imcfunctionlib.functions
' dim xint as integer
' xint = funcs.tabletodbf(dspslips, "netcsv.dbf", 5)
' xint = funcs.tabletodbf(dsletsumtt2, "letsumtt.dbf", 27)
tabletodbf = 0
Dim oconn_ As New SqlConnection("data source=d5z0071;database=imc;integrated security=sspi;")
Dim oconn_d_ As New OdbcConnection("Driver={Microsoft dBase Driver (*.dbf)};UID=admin;usercommitsync=yes;threads=3;statistics=0;safetransaction s=0;pagetimeout=5;maxscanrows=8;maxbuffersize=2048;FIL=dBaseIV;DriverID=533;deleted=0;defaultdir=f:\imcapps\dbffiles;dbq=f:\imcapps\dbffiles;collatingsequence=ascii;")
oconn_.Open()
oconn_d_.Open()
Dim path As String = "f:\imcapps\dbffiles\" & mdbf
Dim underscorename As String
underscorename = Mid(mdbf, 1, mdbf.Length - 4) & "_.dbf"
Dim fi As FileInfo = New FileInfo(path)
If fi.Exists = True Then
Kill("f:\imcapps\dbffiles\" & mdbf)
End If
FileCopy("f:\imcapps\dbffiles\" & underscorename, "f:\imcapps\dbffiles\" & mdbf)
' always save an empty file with _ as a convention
Dim da_d As New OdbcDataAdapter("select * from f:\imcapps\dbffiles\" & mdbf, oconn_d_)
Dim ds_d As New DataSet("_d")
da_d.Fill(ds_d, "_d")
Dim commandbuilder_ds_d As OdbcCommandBuilder = New OdbcCommandBuilder(da_d)
Dim i As Integer
Dim irow, mrow_d As DataRow
For Each irow In mtable.Tables(0).Rows
mrow_d = ds_d.Tables(0).NewRow()
For i = 0 To numcols - 1
mrow_d(i) = irow(i)
Next
ds_d.Tables("_d").Rows.Add(mrow_d)
Next
Try
da_d.Update(ds_d, "_d")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
oconn_.Close()
oconn_d_.Close()
tabletodbf = 1
End Function
I am not so sure... you may try if it works.

check for uniqueness of employee id number

Cant seem to figure out how to check for a unique Employee id Number. I know the validation has to go in the form load, just not sure how to go about it.
Public Class Form1
Dim filename As String
Dim dataFile As System.IO.File
Dim dataWrite As System.IO.StreamWriter
''LOADING AND WRITE TO TEXT DOCUMENT
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'asks user for file name
filename = InputBox("Enter output file name")
If IO.File.Exists(filename) Then
dataWrite = IO.File.AppendText(filename)
Else
MessageBox.Show("filename does not exist")
filename = InputBox("Enter output file name")
dataWrite = IO.File.CreateText(filename)
End If
cboDepart.Items.Add("Accounting")
cboDepart.Items.Add("Administration")
cboDepart.Items.Add("Marketing")
cboDepart.Items.Add("MIS")
cboDepart.Items.Add("Sales")
End Sub
'------
Public EMPLOYEEIDS As String
Dim employeeID1 As ServerData()
Dim employeeID2 As ServerData()
Dim reader As String = My.Computer.FileSystem.ReadAllText("servers.lst")
Dim s() As String
Dim Totalemployeeids As String = CStr(reader.Length)
Dim x As Integer = 0
Dim myArray As String() = reader.Split("|"c)
For x = 1 To Totalemployeeids
employeeID1(x).ServerName = myArray(0)
employeeID2(x).IDname = myarray(0)
Form1_load.ListBox1.Items.Add(Servers(x).ServerName)
x += 1
Next
Structure ServerData
End Structure
End Class
You usually do not insert a unique ID from the client side. Instead, it is inserted automatically by the database server. There is a way to retrieve an inserted ID back, if you need it for display (can also act as a confirmation that a record was successfully inserted):
SELECT SCOPE_IDENTITY()
An example is shown in this answer:
How to get last inserted id? (C#)
On the client side, you need to implement insertion of everything but the ID, in this case you don't need to check for uniqueness. There may be other validation issues upon commit though (unique key violation, data type mismatch) - make sure you catch exceptions and display them to the user as appropriate.

Vb.Net - Copy files based on pattern

I have got table named FILELISTS
Table Name - Filelists
Field - FileNames
Data Value
File1.txt
File2.csv
File3*.csv
I'm struggling to write the code, as per above if it has a file name (like file1.txt and file2.txt) it needs to copy from source to destination. If file name is pattern (like File3*.csv) then copy all files that matches this pattern from source to destination.
I'm enumerating through above row in Vb.net using data reader.
You can use Directory.EnumerateFiles and File.Copy, for example:
var filePatterns = database.GetFileNamePattern(); // your method that returns the list of files
// assuming you've stored the source- and dest.-directories in the app-settings
string sourceFolder = Properties.Settings.Default.SourceFolder;
string destFolder = Properties.Settings.Default.DestinationFolder;
foreach (string pattern in filePatterns)
{
var files = Directory.EnumerateFiles(
sourceFolder,
pattern,
SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
File.Copy(file, Path.Combine(destFolder, Path.GetFileName(file)), true);
}
}
Edit: Sorry, here the VB.NET version:
' your method that returns the list of files:
Dim filePatterns = database.GetFileNamePattern()
' assuming you've stored the source- and dest.-directories in the app-settings
Dim sourceFolder As String = My.Settings.SourceFolder
Dim destFolder As String = My.Settings.DestinationFolder
For Each pattern As String In filePatterns
Dim files = Directory.EnumerateFiles(sourceFolder, pattern, SearchOption.TopDirectoryOnly)
For Each file As String In files
IO.File.Copy(file, IO.Path.Combine(destFolder, IO.Path.GetFileName(file)), True)
Next
Next
DirectoryInfo, FileInfo - - You deleted your other question before I could click post... but this works with .net framework 2.0, like you asked
Option Strict On
Imports sO = System.IO.SearchOption
Imports dI = System.IO.DirectoryInfo
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each F In (New dI("C:\")).GetFiles("*.*", sO.TopDirectoryOnly)
MsgBox(F.FullName)
'Do your copy here
Next
End Sub
End Class