I have built a program that allows the user to search for a customer or add a new user with various information related to that customer. However when I run the program I get an error that says An unhandled exception of type 'System.OverflowException' occurred in Microsoft.VisualBasic.dll attached to the telephone number. I am not sure what I am doing wrong here.
My code:
Imports System.IO
Public Class Form1
Dim txtFile As StreamWriter ' object variable
Dim searchFile As StreamReader ' object variable
' structure declaration
Structure CustomerAccounts
Dim Records As StreamReader
Dim LastName As String
Dim FirstName As String
Dim CustomerNumber As String
Dim Address As String
Dim City As String
Dim State As String
Dim ZIPCode As Integer
Dim TelephoneNumber As Int64
Dim AccountBalance As Double
Dim DateOfLastPayment As String
End Structure
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub SaveCtrlSToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveCtrlSToolStripMenuItem.Click
Dim CustomerRecord As CustomerAccounts ' Structure Variable
' Assigning data to structure variable
CustomerRecord.LastName = txtLast.Text
CustomerRecord.FirstName = txtFirst.Text
CustomerRecord.CustomerNumber = txtNumber.Text
CustomerRecord.Address = txtAddress.Text
CustomerRecord.City = txtCity.Text
CustomerRecord.State = txtState.Text
CustomerRecord.ZIPCode = CInt(txtZIPCode.Text)
CustomerRecord.TelephoneNumber = CInt(txtTelephone.Text)
CustomerRecord.AccountBalance = CDbl(txtAccountBalance.Text)
While CustomerRecord.AccountBalance < 0
CustomerRecord.AccountBalance = CDbl(InputBox("Please enter a non-negative balance"))
End While
CustomerRecord.DateOfLastPayment = CDate(txtPayment.Text)
' Opening a file in append mode
txtFile = File.CreateText("Records.txt")
' Writing data to a file
txtFile.WriteLine(CustomerRecord.LastName)
txtFile.WriteLine(CustomerRecord.FirstName)
txtFile.WriteLine(CustomerRecord.CustomerNumber)
txtFile.WriteLine(CustomerRecord.Address)
txtFile.WriteLine(CustomerRecord.City)
txtFile.WriteLine(CustomerRecord.State)
txtFile.WriteLine(CustomerRecord.ZIPCode)
txtFile.WriteLine(CustomerRecord.TelephoneNumber)
txtFile.WriteLine(CustomerRecord.AccountBalance)
txtFile.WriteLine(CustomerRecord.DateOfLastPayment)
txtFile.Close() ' Close the data file after writing the data
clearFields()
End Sub
Private Sub ExitCtrlQToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitCtrlQToolStripMenuItem.Click
' Close the form
Me.Close()
End Sub
Private Sub SearchToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles SearchToolStripMenuItem1.Click
' Open a file in read mode
searchFile = File.OpenText("Records.Txt")
Dim lastName As String
Dim flag As Integer
flag = 0
' get the record name from user input
lastName = InputBox("Please enter the last name to search")
Dim CSearchRecord As CustomerAccounts
Try
While Not searchFile.EndOfStream
CSearchRecord.LastName = searchFile.ReadLine()
CSearchRecord.FirstName = searchFile.ReadLine()
CSearchRecord.CustomerNumber = searchFile.ReadLine()
CSearchRecord.Address = searchFile.ReadLine()
CSearchRecord.City = searchFile.ReadLine()
CSearchRecord.State = searchFile.ReadLine()
CSearchRecord.ZIPCode = searchFile.ReadLine()
CSearchRecord.TelephoneNumber = searchFile.ReadLine()
CSearchRecord.AccountBalance = searchFile.ReadLine()
CSearchRecord.DateOfLastPayment = searchFile.ReadLine()
' Compare current record with search record
If CSearchRecord.LastName.Equals(lastName) Then
flag = 1
Exit While
End If
End While
' If record found display txt fields
If flag.Equals(1) Then
txtLast.Text = CSearchRecord.LastName.ToString()
txtFirst.Text = CSearchRecord.FirstName.ToString()
txtNumber.Text = CSearchRecord.CustomerNumber.ToString()
txtAddress.Text = CSearchRecord.Address.ToString()
txtCity.Text = CSearchRecord.City.ToString()
txtState.Text = CSearchRecord.City.ToString()
txtZIPCode.Text = CSearchRecord.ZIPCode.ToString()
txtTelephone.Text = CSearchRecord.TelephoneNumber.ToString()
txtAccountBalance.Text = CSearchRecord.AccountBalance.ToString()
txtPayment.Text = CSearchRecord.DateOfLastPayment.ToString()
Else
' If record not found alert user
MessageBox.Show("Record Not Found")
clearFields()
End If
Catch ex As Exception
End Try
End Sub
Private Sub ReportToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ReportToolStripMenuItem1.Click
Dim report As String
report = "Report of Customer Accounts" + vbNewLine
' Open file in read mode
searchFile = File.OpenText("Record.txt")
Try
' Reading the file until end
While Not searchFile.EndOfStream
report += searchFile.ReadLine() + " "
report += searchFile.ReadLine() + " "
report += searchFile.ReadLine() + " "
report += searchFile.ReadLine() + " "
report += vbNewLine
End While
Catch ex As Exception
End Try
' Display file Content as report
MessageBox.Show(report)
End Sub
Private Sub clearFields()
txtAccountBalance.Clear()
txtAddress.Clear()
txtCity.Clear()
txtFirst.Clear()
txtLast.Clear()
txtNumber.Clear()
txtPayment.Clear()
txtState.Clear()
txtTelephone.Clear()
txtZIPCode.Clear()
End Sub
End Class
Any help offered would be greatly appreciated. I just need to know how to fix this.
Related
I need to understand if there is a possibility, within VB.NET, to be able to read the columns of an Excel file and write them out to a CSV file in a different order.
In practice, the Excel file we are sent has 6 columns: "amount", "branch", stock "," proposal "," quantity "," type ". The company management system accepts the text file with the columns in a different order: "branch", "stock", "amount", "quantity", "type", "proposal". This creates a problem for me because when I go to convert it my ERP fails to recognize that the column is in a different position.
I arrive at the concrete question, I would like to have the possibility to read the columns and make it possible through a script to be able to position them according to the position I decide.
I tried this code for import and convert to txt, but I need another script:
Imports System.IO
Imports ExcelDataReader
Imports System.Text
Public Class Form1
Dim tables As DataTableCollection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "(*.xls)|*.xls|(*.xls)|*.xlsx"}
If ofd.ShowDialog() = DialogResult.OK Then
txtFileName.Text = ofd.FileName
Using Stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(Stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
tables = result.Tables
cboSheet.Items.Clear()
For Each table As DataTable In tables
cboSheet.Items.Add(table.TableName)
Next
End Using
End Using
End If
End Using
End Sub
Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged
Dim dt As DataTable = tables(cboSheet.SelectedItem.ToString())
dgProposte.DataSource = dt
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim writer As TextWriter = New StreamWriter("C:\Users\antonio\Desktop\Prova.txt")
For i As Integer = 0 To dgProposte.Rows.Count - 2 Step +1
For j As Integer = 0 To dgProposte.Columns.Count - 1 Step +1
writer.Write(vbTab & dgProposte.Rows(i).Cells(j).Value.ToString() & vbTab & "")
Next
writer.WriteLine("")
Next
writer.Close()
MessageBox.Show("Dati Esportati")
End Sub
The tables that you get from importing the Excel sheet(s) have their column names set, and you can index the column by its name.
So, and with a little adjustment to factor out some methods:
Imports System.IO
Imports ExcelDataReader
Public Class Form1
Dim tables As DataTableCollection
Private Sub WriteToCsv(tableName As String, filename As String)
Dim columnWriteOrder = {"branch", "stock", "amount", "quantity", "type", "proposal"}
Using writer As TextWriter = New StreamWriter(filename)
Dim tbl = tables(tableName)
For i As Integer = 0 To dgProposte.Rows.Count - 2
Dim vals As New List(Of String)
For j As Integer = 0 To columnWriteOrder.Length - 1
Dim val = tbl.Rows(i).Item(columnWriteOrder(j)).ToString()
vals.Add(val)
Next
writer.WriteLine(String.Join(vbTab, vals))
Next
End Using
End Sub
Private Sub PopulateSheetNames()
cboSheet.Items.Clear()
For Each table As DataTable In tables
cboSheet.Items.Add(table.TableName)
Next
End Sub
Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged
If cboSheet.SelectedIndex >= 0 Then
Dim tableName = cboSheet.SelectedItem.ToString()
Dim dt As DataTable = tables(tableName)
dgProposte.DataSource = dt
End If
End Sub
Private Sub bnLoad_Click(sender As Object, e As EventArgs) Handles bnLoad.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls", .InitialDirectory = "C:\temp"}
If ofd.ShowDialog() <> DialogResult.OK Then
Exit Sub
End If
txtFileName.Text = ofd.FileName
Using Stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(Stream)
Dim edsc = New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}}
Dim result As DataSet = reader.AsDataSet(edsc)
tables = result.Tables
End Using
End Using
PopulateSheetNames()
End Using
End Sub
Private Sub bnSaveAsCsv_Click(sender As Object, e As EventArgs) Handles bnSaveAsCsv.Click
If cboSheet.SelectedIndex < 0 Then
MessageBox.Show("Please select a sheet name.", "No sheet name selected", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Sub
End If
Dim sheetName = cboSheet.SelectedItem.ToString()
If Not String.IsNullOrEmpty(sheetName) Then
WriteToCsv(sheetName, "C:\temp\Prova.csv")
MessageBox.Show("Dati Esportati.", "Dati Esportati", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
I changed the names of the buttons because "Button1" and "Button2" are not descriptive.
(I set the .InitialDirectory of the OpenFileDialog because it was convenient for me.)
Why you don't map a DTO of your data table?
Public Class MioDto
Property campoUno As String
Property campoDue As String
'...ecc
End Class
and then you can fill a dto in a cicle or so...
Dim a As New MioDto() With {.campoUno="...", campoDue="..."}
or if you want you can use
https://github.com/AutoMapper/AutoMapper
When you have a Dto class filled you can use it for generate your txt with youor preferred order.
So I have some json formatted data, in which an article name (the field in my case is "description courte") can be used multiple times and have a different price each time, I want to get those prices and display them in a listbox and let the user pick which one to parse in the column "price" which is found.offset(0,3). Note that I only search for fields that exist in the Range("G:G") This is what I did so far :
This code is returning an error : index does not belong in the selection (sorry if translated badly) at the
Set Found = Range("G:G").Find(ArtDict.Items()(Index).Name)
Code example
Sub prix()
Dim http As New WinHttpRequest
Dim resp As String
Dim url As String
url = "https://api.airtable.com/v0/appY6Wo3AmLHqHkjr/Materiaux?api_key=key_here" & Fields
http.Open "GET", url, False
http.Send
Dim JSON As Object
Dim Found As Range
Dim ArtDict As New Dictionary, Article As class_Article
Dim Index As Long, count As Long
Set JSON = JsonConverter.ParseJson(http.ResponseText)
For Index = 1 To JSON("records").count
Set Found = Range("G:G").Find(ArtDict.Items()(Index).Name)
If Not ArtDict.Exists(JSON("records")(Index)("fields")("description courte")) Then
'If this article doesn't exist in the article dictionary, then create the article object and add it to the dictionary
Set Article = New class_Article
Article.Name = JSON("records")(Index)("fields")("description courte")
Article.ParsePrice JSON("records")(Index)("fields")("prix unitaire HT")
Debug.Print Article.Name, Article.HighPrice, Article.LowPrice
ArtDict.Add Article.Name, Article
Else
Set Article = ArtDict(JSON("records")(Index)("fields")("description courte"))
Article.ParsePrice JSON("records")(Index)("fields")("prix unitaire HT")
Debug.Print Article.Name, Article.HighPrice, Article.LowPrice
Set ArtDict(JSON("records")(Index)("fields")("description courte")) = Article
End If
If Not Found Is Nothing Then
count = Found.Offset(0, 4).Value + 1
If count > 1 Then
UserForm1.Show
UserForm1.ListBox1.AddItem (Article.HighPrice)
UserForm1.ListBox1.AddItem (Article.LowPrice)
Found.Offset(0, 3) = UserForm1.ListBox1.Value
End If
End If
Next Index
End Sub
JSON SAMPLE
{
"records": [
{
"id": "rec0MS66BnYY0vK32",
"fields": {
"id": 124,
"article": "osmo 24m2 3062MAT 0.75L",
"categorie": [
"recvw95DBiWvk3zaH"
],
"udv": 1,
"unité": [
"recYQ9wpLDgNDk5BW"
],
"prix HT de l'udv": 29.09,
"date d'achat": "2019-08-01",
"distributeur": "cotet mtp",
"reference distributeur": "OSMO-ORI-0.75-M",
"id facture": "FA19036300",
"created on": "2020-02-07",
"by": "remyvignaux",
"description courte": "osmo 3062MAT",
"prix unitaire HT": 29.09
},
"createdTime": "2021-02-28T20:53:00.000Z"
},....etc
CLASS_ARTICLE
Option Explicit
Public Name As String
Public HighPrice As Currency
Public LowPrice As Currency
Private Sub Class_Initialize()
HighPrice = -922337203685477.5807# 'Set value to lowest possible value
LowPrice = 922337203685477.5807# 'Set value to the highest possible value
End Sub
Public Function ParsePrice(ByVal NewPrice As Currency) As Boolean
HighPrice = IIf(NewPrice > HighPrice, NewPrice, HighPrice)
LowPrice = IIf(NewPrice < LowPrice, NewPrice, LowPrice)
End Function
Parse the JSON into a collection of articles (using a dictionary) and then process each article in turn. The price selection can be an article method. I used an input box just to show the principle but you could use listbox. The results are shown on Sheet1.
Option Explicit
Sub prix()
' get json into a string
Dim fso, ts, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\temp\json.txt")
s = ts.ReadAll
ts.Close
Dim dictArt As New Dictionary, oArt As Class_Article ' holds articles
Dim name As String, price As Currency
Dim JSON As Object, rec, fld
Set JSON = JsonConverter.ParseJson(s)
' parse json
For Each rec In JSON("records")
Set fld = rec("fields")
name = fld("description courte")
price = fld("prix unitaire HT")
If dictArt.Exists(name) Then
dictArt(name).AddPrice price
Else
Set oArt = New Class_Article
oArt.name = name
oArt.AddPrice price
dictArt.Add name, oArt
End If
Next
' result to sheet1
Dim key, i As Long: i = 1
Sheet1.Cells.Clear
Sheet1.Range("A1:C1") = Array("Description", "Price Count", "Price")
For Each key In dictArt
i = i + 1
Set oArt = dictArt(key)
Sheet1.Cells(i, 1) = oArt.Name
Sheet1.Cells(i, 2) = oArt.PriceCount
' if more than once give options
If oArt.PriceCount > 1 Then
Sheet1.Cells(i, 1).Select
Sheet1.Cells(i, 3).Interior.Color = vbYellow
oArt.SelectPrice
If oArt.bSelected Then
Sheet1.Cells(i, 3) = oArt.price
Sheet1.Cells(i, 3).Interior.Color = xlNone
End If
Else
Sheet1.Cells(i, 3) = oArt.price
End If
Next
End Sub
' Class_Article
Public name As String
Public price As Currency
Public PriceCount As Integer
Public bSelected As Boolean
Private prices As New Collection
Private i As Integer
Public Sub AddPrice(ByVal price As Currency)
PriceCount = PriceCount + 1
Me.price = price
prices.Add price, CStr(PriceCount)
End Sub
Sub SelectPrice()
Dim msg As String
bSelected = False
' build option list
msg = name & " has " & PriceCount & " prices"
For i = 1 To PriceCount
msg = msg & vbCr & "(" & i & ") " & prices(i)
Next
' user selects
begin:
i = Application.InputBox(msg, "Select Price 1 to " & PriceCount, 1, Type:=1) ' int
If i < 1 Then
Exit Sub
ElseIf i > PriceCount Then
GoTo begin
End If
' selected price
price = prices(i)
bSelected = True
End Sub
I have this vb.net code that works great for merging all PDF's in a directory path based on criteria that the PDF contains within. The new problem is that this directory will have 1000+ pdf's, and a user will have a list of specific PDF's by their file name in a column in excel that will need to be split/merged by said criteria for that particular day.
lets say for example a directory has
ZTEST11.SAMPLE01
ZTEST12.SAMPLE02
ZTEST13.SAMPLE03
ZTEST14.SAMPLE04
ZTEST15.SAMPLE05
ZTESTN+1....
But out of all of those, my excel file in column A has listed only (and the row numbers will change daily):
ZTEST11.SAMPLE01
ZTEST13.SAMPLE03
ZTEST15.SAMPLE05
So those are the only files that i want my code to affect.
My code is this
Module Module1
Class PageType
Property Identifier As String
Property TypeName As String
End Class
Sub Main(ByVal args As String())
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim range As Excel.Range
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("C:\Users\XBorja.RESURGENCE\Desktop\xavier.xlsx")
xlWorkSheet = xlWorkBook.Worksheets("sheet1")
range = xlWorkSheet.UsedRange
Dim dir = "G:\Word\Department Folders\Pre-Suit\Drafts-IL\2-IL_AttyReview\2018-09\Reviewed\"
Dim unmerged = Combine(dir, "unmerged")
' Set up a list of the identifiers to be searched for and the corresponding names to be used in the filename.
Dim pageTypes As New List(Of PageType)
Dim ids = {"COVERSPLIT", "COMPLAINTSPLIT", "EXHIBITSPLIT", "MILSPLIT", "SUMSPLIT"}
Dim nams = {" Cover Sheet ", " Complaint ", " Exhibit ", " Military ", " Summons "}
' For Each inputfile As String In Directory.GetFiles(dir, "*.pdf")
For Each aCell In range
MsgBox(aCell.Value)
For Each inputfile As String In Combine(dir, aCell.value)
For i = 0 To ids.Length - 1
pageTypes.Add(New PageType With {.Identifier = ids(i), .TypeName = nams(i)})
Next
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
Dim extractor As New TextExtractor()
' Load sample PDF document
extractor.LoadDocumentFromFile(inputfile)
Dim pageCount = extractor.GetPageCount()
Dim currentPageTypeName = "UNKNOWN"
Dim Path As String = IO.Path.GetFileNameWithoutExtension(inputfile)
Dim extracted = Path.Substring(0, 7)
' Search each page for a keyword
For i = 0 To pageCount - 1
' Find the type of the current page
' If it is not present on the page, then the last one found will be used.
For Each pt In pageTypes
If extractor.Find(i, pt.Identifier, False) Then
currentPageTypeName = pt.TypeName
End If
Next
' Extract page
Using splitter As New DocumentSplitter() With {.OptimizeSplittedDocuments = True}
Dim pageNumber = i + 1 ' (!) page number in ExtractPage() is 1-based
If Not Directory.Exists(dir & "\unmerged") Then
Directory.CreateDirectory(dir & "\unmerged")
End If
Dim outputfile = Combine(unmerged, extracted & currentPageTypeName & pageNumber & ".pdf")
splitter.ExtractPage(inputfile, outputfile, pageNumber)
Console.WriteLine("Extracted page " & pageNumber & " to file """ & outputfile & """")
End Using
Next
extractor.Dispose()
Next ' for each
Next
Call Xavier()
End Sub
As you can see i added in the part so that my excel book opens, and reads off to me each cell value in column A which are the file numbers of the PDF's i want merged.
That works fine. But how do i get those values into my code so that the code knows those are the specific PDF files i want merged in that selected directory?
You can see what i commented out: For Each inputfile As String In Directory.GetFiles(dir, "*.pdf")
Thats what i used before so that my code would merge all the PDF's in that directory based on the criteria i defined.
How do i correct this so that my cell values turn to string values so that my code can iterate through each cell value as PDF file in my directory to have them selected for merge?
Solution:
Option Infer On
'Option Strict On
Imports Bytescout.PDFExtractor
Imports System.Collections
Imports System.Collections.Generic
Imports System.IO.Path
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System
Imports System.Diagnostics
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO
Imports System.Deployment
Imports ExcelDataReader
Imports Microsoft
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Core
Imports Microsoft.Office.Interop.Excel
Module Module1
Class PageType
Property Identifier As String
Property TypeName As String
End Class
Sub Main(ByVal args As String())
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim range As Excel.Range
Dim aCell As Object
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("C:\Users\XBorja.RESURGENCE\Desktop\xavier.xlsx")
xlWorkSheet = xlWorkBook.Worksheets("sheet1")
range = xlWorkSheet.UsedRange
Dim dir = "G:\Word\Department Folders\Pre-Suit\Drafts-IL\2-IL_AttyReview\2018-09\Reviewed\"
'Dim inputfile = Combine(dir, Obj.value)
Dim unmerged = Combine(dir, "unmerged")
' Set up a list of the identifiers to be searched for and the corresponding names to be used in the filename.
Dim pageTypes As New List(Of PageType)
Dim ids = {"COVERSPLIT", "COMPLAINTSPLIT", "EXHIBITSPLIT", "MILSPLIT", "SUMSPLIT"}
Dim nams = {" Cover Sheet ", " Complaint ", " Exhibit ", " Military ", " Summons "}
' For Each inputfile As String In Directory.GetFiles(dir, "*.pdf")
For Each aCell In range
MsgBox(aCell.Value)
Dim file1 = aCell.Value & ".pdf"
For Each inputfile As String In Directory.GetFiles(dir, file1)
For i = 0 To ids.Length - 1
pageTypes.Add(New PageType With {.Identifier = ids(i), .TypeName = nams(i)})
Next
Dim extractor As New TextExtractor()
' Load sample PDF document
extractor.LoadDocumentFromFile(inputfile)
Dim pageCount = extractor.GetPageCount()
Dim currentPageTypeName = "UNKNOWN"
Dim Path As String = IO.Path.GetFileNameWithoutExtension(inputfile)
Dim extracted = Path.Substring(0, 7)
' Search each page for a keyword
For i = 0 To pageCount - 1
' Find the type of the current page
' If it is not present on the page, then the last one found will be used.
For Each pt In pageTypes
If extractor.Find(i, pt.Identifier, False) Then
currentPageTypeName = pt.TypeName
End If
Next
' Extract page
Using splitter As New DocumentSplitter() With {.OptimizeSplittedDocuments = True}
Dim pageNumber = i + 1 ' (!) page number in ExtractPage() is 1-based
If Not Directory.Exists(dir & "\unmerged") Then
Directory.CreateDirectory(dir & "\unmerged")
End If
Dim outputfile = Combine(unmerged, extracted & currentPageTypeName & pageNumber & ".pdf")
splitter.ExtractPage(inputfile, outputfile, pageNumber)
Console.WriteLine("Extracted page " & pageNumber & " to file """ & outputfile & """")
End Using
Next
extractor.Dispose()
Next ' for each
Next
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
Call Xavier()
End Sub
Private Sub releaseObject(ByVal aCell As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(aCell)
aCell = Nothing
Catch ex As Exception
aCell = Nothing
Finally
GC.Collect()
End Try
End Sub
End Module
Module Module2
Private inputdir As String = "G:\Word\Department Folders\Pre-Suit\Drafts-IL\2-IL_AttyReview\2018-09\Reviewed\unmerged\"
Public Sub Xavier()
MergeFiles("Cover Sheet", inputdir)
MergeFiles("Complaint", inputdir)
MergeFiles("Exhibit", inputdir)
MergeFiles("Military", inputdir)
MergeFiles("Summons", inputdir)
End Sub
Public Sub MergeFiles(ByVal name As String, inputdir As String)
Dim OutputFile As String
Dim OutputDir As String = inputdir & "\Merge\"
Dim OutputDocument As PdfDocument
If Not Directory.Exists(OutputDir) Then Directory.CreateDirectory(OutputDir)
For Each files As String In Directory.GetFiles(inputdir, "*" & name & "*.pdf")
OutputFile = GetFileNameWithoutExtension(files).Substring(0, 7) & " " & name & ".pdf"
If File.Exists(OutputDir & OutputFile) Then
OutputDocument = PdfReader.Open(OutputDir & OutputFile)
Else
OutputDocument = New PdfDocument()
End If
Console.WriteLine("Merging: {0}...", GetFileName(files))
Using InputDocument As PdfDocument = PdfReader.Open(files, PdfDocumentOpenMode.Import)
For Each page As PdfPage In InputDocument.Pages
OutputDocument.AddPage(page)
Next
End Using
OutputDocument.Save(OutputDir & OutputFile)
OutputDocument.Dispose()
Next
End Sub
End Module
I have a dialog form here where a user can upload a file from Excel and import and display to the datagrid view. However, my problem is when the user closes the application or form, the datagridview was empty and reset.
My question is how can I retrieve its data and display it, every time the user will open the form. Is it possible if the data was not saved in the database and will only based on the uploaded or imported Excel file? And if the user has uploaded a new Excel, I want to replace the existing rows or data in the datagridview.
I really hope you would help.
Below you can find my code:
Imports System.Data
Public Class frmSupplier
Private Sub btn_upload_supplier_Click(sender As Object, e As EventArgs) Handles btn_upload_supplier.Click
Try
If btn_upload_supplier.Text = "New" Then
Dim Openfile As New OpenFileDialog
Openfile.ShowDialog()
txtpath_supplier.Text = Openfile.FileName
Label1.Text = txtpath_supplier.Text
If txtpath_supplier.Text = Nothing Then
Else
btn_upload_supplier.Text = "Upload"
End If
ElseIf btn_upload_supplier.Text = "Upload" Then
Dim dtItemlist As New DataTable
Dim obj As New Basegeneral
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + txtpath_supplier.Text.ToString() + "; Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
dg_details.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MessageBox.Show(Me, ex.ToString, "Error:")
End Try
End If
Catch ex As Exception
MessageBox.Show(Me, ex.ToString, "Error:")
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim row As System.Data.DataRow = GridView1.GetDataRow(GridView1.FocusedRowHandle)
If row.Item(0).ToString = "" Then
MessageBox.Show("Please select supplier to remove", "KCC Retail System")
Return
End If
If DevExpress.XtraEditors.XtraMessageBox.Show("Are you sure you want to remove supplier '" & row.Item(0) & "'?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("Supplier " & row.Item(0) & " has been removed!", "KCC Retail System")
GridView1.DeleteRow(GridView1.FocusedRowHandle)
Else
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error :")
End Try
End Sub
Private Sub btn_clear_Click(sender As Object, e As EventArgs) Handles btn_clear.Click
btn_upload_supplier.Text = "New"
txtpath_supplier.Text = ""
End Sub
The form will be open when the user click the button and it will display as a dialog (ShowDialog).
To save and then re-hydrate the contents of a DataGridView you can use a binary formatter.
Imports System.IO
Import System.Runtime.Serialization.Formatters.Binary
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim FileName As String = "MyData.dat" 'Will save in bin directory
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
' 1. Create an instance of a Binary Formatter
Dim bf As New BinaryFormatter
' 2. Create a file stream passing in (the name of the file to create, mode: Create, access: Write, share: none)
Using fs As Stream = New FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None)
' 3. use the Serialize method of the Binary Formatter passing in the file stream(file name, create, write, no share) And the object
bf.Serialize(fs, dt)
End Using
End Sub
Private Sub btnFillFromFill_Click(sender As Object, e As EventArgs) Handles btnFillFromFill.Click
Dim FileName As String = "MyData.dat"
Dim dt As DataTable
' 1. Create an instance of Binary Formatter
Dim bf As New BinaryFormatter()
' 2. Get an instance of a FileStream for the OpenRead method of File passing in (the fileName)
Using fs As Stream = File.OpenRead(FileName)
' 3. cast back to original object, the Deserialize method of the Binary Formatter passing in the File Stream
dt = CType(bf.Deserialize(fs), DataTable)
End Using
DataGridView1.DataSource = dt
End Sub
I need to export a lotus notes view to excel. The problem is, I have two columns in the view which displays multiple values with "New line" as the separator. I tried the inbuilt export function as well as with a new lotus script export function with few formatting. In both the cases the multiple values cannot be made to appear in one cell. Only the first value is displayed in each row. The rest of the values are ignored. Our User wants the excel report only with Multiple values in New line and not with any other delimiter.
Kindly help me with your suggestions. I am using Lotus notes 6.5 and Microsoft office 2010.
Thank you.
Write the export in Lotusscript. Not hard, and you get full control of the export.
If the fields are multi-value fields, simply read the values as a variant and then write them to the output file with newline between each item.
Here is one idea of how to solve it:
%REM
Agent View Export
Created Mar 27, 2013 by Karl-Henry Martinsson
Description: Code to export a specified view as CSV.
Copyright (c) 2013 by Karl-Henry Martinsson
This code is distributed under the terms of
the GNU General Public License V3.
See http://www.gnu.org/licenses/gpl.txt
%END REM
Option Public
Option Declare
Class RowData
Public column List As String
Public Sub New()
End Sub
Public Sub SetColumnHeader(view As NotesView)
Dim viewcolumn As NotesViewColumn
Dim cnt As Integer
ForAll vc In view.Columns
Set viewcolumn = vc
column(CStr(cnt)) = viewcolumn.Title
cnt = cnt + 1
End Forall
End Sub
Public Sub SetColumnValues(values As Variant)
Dim cnt As Integer
Dim tmp As String
ForAll v In values
If IsArray(v) Then
ForAll c In v
tmp = tmp + c + Chr$(13)
End ForAll
column(CStr(cnt)) = Left$(tmp,Len(tmp)-1)
Else
column(CStr(cnt)) = v
End If
cnt = cnt + 1
End ForAll
End Sub
End Class
Class CSVData
Private row List As RowData
Private rowcnt As Long
%REM
Function New
Description: Open the view and read view data
into a list of RowData objects.
%END REM
Public Sub New(server As String, database As String, viewname As String)
Dim db As NotesDatabase
Dim view As NotesView
Dim col As NotesViewEntryCollection
Dim entry As NotesViewEntry
Dim colcnt As Integer
Set db = New NotesDatabase(server, database)
If db Is Nothing Then
MsgBox "Could not open " + database + " on " + server,16,"Error"
Exit Sub
End If
Set view = db.GetView(viewname)
If view Is Nothing Then
MsgBox "Could not access view " + viewname + ".",16,"Error"
Exit Sub
End If
Set col = view.AllEntries()
rowcnt = 0
Set entry = col.GetFirstEntry()
Set row("Header") = New RowData()
Call row("Header").SetColumnHeader(view)
Do Until entry Is Nothing
rowcnt = rowcnt + 1
Set row(CStr(rowcnt)) = New RowData()
Call row(CStr(rowcnt)).SetColumnValues(entry.ColumnValues)
Set entry = col.GetNextEntry(entry)
Loop
End Sub
%REM
Function CSVArray
Description: Returns a string array of CSV data by row
%END REM
Public Function CSVArray() As Variant
Dim rowarray() As String
Dim textrow As String
Dim cnt As Long
ReDim rowarray(rowcnt) As String
ForAll r In row
textrow = ""
ForAll h In r.column
textrow = textrow + |"| + Replace(h,Chr$(13),"\n") + |",|
End ForAll
rowarray(cnt) = Left$(textrow,Len(textrow)-1)
cnt = cnt + 1
End ForAll
CSVArray = rowarray
End Function
%REM
Function HTMLArray
Description: Returns a string array of HTML data by row
%END REM
Public Function HTMLArray() As Variant
Dim rowarray() As String
Dim textrow As String
Dim cnt As Long
ReDim rowarray(rowcnt) As String
ForAll r In row
textrow = ""
ForAll h In r.column
textrow = textrow + |<td>| + Replace(h,Chr$(13),"<br>") + |</td>|
End ForAll
rowarray(cnt) = "<tr>" + textrow + "</tr>"
cnt = cnt + 1
End ForAll
HTMLArray = rowarray
End Function
End Class
%REM
********************************
Example of how to call the class
********************************
%END REM
Sub Initialize
Dim csv As CSVData
Dim outfile As String
Set csv = New CSVData("DominoServer/YourDomain", "names.nsf", "People\By Last Name")
outfile = "c:\ExcelExportTest.csv"
Open outfile For Output As #1
ForAll row In csv.CSVArray()
Print #1, row
End ForAll
Close #1
outfile = "c:\ExcelExportTest.xls"
Open outfile For Output As #2
Print #2, "<table>"
ForAll row In csv.HTMLArray()
Print #2, row
End ForAll
Print #2, "</table>"
Close #2
End Sub