Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports iTextSharp.text
- Imports iTextSharp.text.api
- Imports iTextSharp.text.pdf
- Imports iTextSharp.text.pdf.parser
- Imports System.Text
- Imports System.IO
- Imports System
- Imports System.Data
- Imports System.Data.OleDb
- Imports System.Text.RegularExpressions
- Imports System.Data.SqlClient
- Imports Microsoft.VisualBasic.CompilerServices
- Imports System.Configuration
- Imports System.DirectoryServices.AccountManagement
- Public Class Visure
- 'Il programma consente la lettura di una serie di file pdf inseriti in input contenenti le visure P.R.A.
- 'riporta i dati acquisiti all’interno del file excel del Cliente anch’esso richiesto in input.
- 'Il programma elaborerà ogni file pdf contenuto nella cartella indicata.
- 'Il pogramma esegue il caricamento dei dati elaborati sul Database specificato nel file .config
- 'N.B. Creare le tabelle: LOG_Operazioni, TB_Operatori, Testate_Excel, Anagrafica, Dettagli, VISURE_PDF se non presenti nel DB.
- 'La stringa per la creazioni delle sopracitate tabelle si troveranno nel file .config
- Public Shared CnSql As SqlConnection
- Dim DirPdf As String
- Dim fileExcel As String
- Dim nProprietari As Integer
- Dim Tab As String
- Dim errors As Integer
- Dim TempTab As String
- Dim TempTabColName(100) As String
- Dim DettagliDtTab As New System.Data.DataTable
- Dim indexColTempTab As Integer
- Dim G_USERFULLNAME As String
- Dim G_ACCOUNTWINDOWS As String
- Dim G_IDOPERATORE As String
- Dim saveExcelDataGrid As System.Data.DataTable
- Dim connectionString As String = My.Settings.ConnString
- Private Sub Exec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Exec.Click
- 'Inizia l'esecuzione del programma. Inserimento dei log relativi. Setup dei nomi delle tabelle presi dal file .config e controllo sui file di input
- Try
- 'setup
- errors = 0
- RegistraLog("Elaborazione iniziata sul programma Visure_Pdf_Excel", "NULL")
- Dim result As DialogResult = Windows.Forms.DialogResult.Yes
- Tab = My.Settings.PDFtab
- TempTab = My.Settings.TempTab
- ProgressBar1.Step = 1
- 'Controllo sui file di input
- If fileExcel = "" Or DirPdf = "" Then
- MsgBox("Selezionare un file excel ed una cartella pdf prima di continuare.")
- Exit Sub
- End If
- If Path.GetFileNameWithoutExtension(fileExcel).Contains("VISURE_PDF") Then
- result = MessageBox.Show("Un file excel già elaborato è stato selezionato, sei sicuro di voler continuare?", "Attenzione!", MessageBoxButtons.YesNo)
- End If
- If result = DialogResult.Yes Then
- ProgressBar1.Visible = True
- ProgressBar1.Step = 10
- ProgressBar1.PerformStep()
- ProgressBar1.Value = 0
- TableDeleter(TempTab)
- CnSqlOpen(connectionString)
- LeggiRinominaPdfByTarga(DirPdf)
- Else
- Exit Sub
- End If
- Catch ex As Exception
- MsgBox("Un errore è stato rilvevato durante l'elaborazione dei file. Errore:" & vbLf & ex.Message)
- Err.Clear()
- End Try
- End Sub
- Public Function LeggiRinominaPdfByTarga(ByVal sFolderPdfs As String) As Boolean
- 'Lettura dei pdf contenuti all'interno della cartella sFolderPdfs e creazione del file di testo relativo utilizzato in seguito per l'estrazione dei dati
- ProgressBar1.Step = 1
- Dim dir As DirectoryInfo
- Dim file As FileInfo
- Dim s As String
- Dim sFileInput As String
- Dim sFileTxt As String
- Dim TableToExcel As New Data.DataTable
- Dim counter As Integer = 0
- Try
- dir = New DirectoryInfo(sFolderPdfs)
- 'Inizio ciclo for per la scansione di ogni singolo file pdf.
- 'All'interno del ciclo verrà richiamato il metodo LeggiTargaEDateDaPdf per l'estrazione dei dati.
- For Each file In dir.GetFiles("*.PDF", SearchOption.TopDirectoryOnly)
- sFileInput = file.Directory.ToString + "\" + file.Name.ToString
- sFileTxt = file.Directory.ToString + "\" + file.Name.ToString.Replace("PDF", "txt")
- 'Creazione del file txt sulla base del file pdf
- s = ParsePdfText(sFileInput)
- My.Computer.FileSystem.WriteAllText(sFileTxt, s, False)
- LeggiTargaEDateDaPdf(sFileTxt, sFileInput)
- counter += 1
- If counter Mod 20 = 0 Then
- ProgressBar1.PerformStep()
- End If
- Next file
- 'Fine della lettura dei file pdf e relativo inserimento dei dati nelle opportune tabelle.
- 'Eliminazione record duplicati all'interno della tabella VISURE_PDF.
- CancellaDuplicatiIdTarga(Tab)
- 'Inizio lettura del file excel
- ExcelManagment(fileExcel)
- Return 0
- Catch ex As Exception
- Return 0
- End Try
- End Function
- Public Shared Function ParsePdfText(ByVal sourcePDF As String, _
- Optional ByVal fromPageNum As Integer = 0, _
- Optional ByVal toPageNum As Integer = 0) As String
- 'Lettura del file pdf sourcePDF selezionato dal metodo LeggiRinominaPdfbyTarga e scrittura del file .txt utilizzto in seguito per la lettura dei dati.
- Dim sb As New System.Text.StringBuilder
- Try
- Dim reader As New iTextSharp.text.pdf.PdfReader(sourcePDF)
- Dim pageBytes() As Byte = Nothing
- Dim token As iTextSharp.text.pdf.PRTokeniser = Nothing
- Dim tknType As Integer = -1
- Dim tknValue As String = String.Empty
- If fromPageNum = 0 Then
- fromPageNum = 1
- End If
- If toPageNum = 0 Then
- toPageNum = reader.NumberOfPages
- End If
- If fromPageNum > toPageNum Then
- Throw New ApplicationException("Errore parametri")
- End If
- For i As Integer = fromPageNum To toPageNum Step 1
- pageBytes = reader.GetPageContent(i)
- If Not IsNothing(pageBytes) Then
- token = New iTextSharp.text.pdf.PRTokeniser(pageBytes)
- While token.NextToken()
- tknType = token.TokenType()
- tknValue = token.StringValue
- Select Case tknType
- Case 1 ' iTextSharp.text.pdf.PRTokeniser.TK_NUMBER
- Dim dValue As Double
- Dim r As Double
- If Double.TryParse(tknValue, dValue, Nothing, r) Then
- If dValue < -8000 Then
- sb.Append(r)
- End If
- End If
- Case 2 ' iTextSharp.text.pdf.PRTokeniser.TK_STRING
- sb.Append(token.StringValue)
- Case 3 ' iTextSharp.text.pdf.PRTokeniser.TK_NAME
- '
- Case 4 ' iTextSharp.text.pdf.PRTokeniser.TK_COMMENT
- '
- Case 5 ' iTextSharp.text.pdf.PRTokeniser.TK_START_ARRAY
- '
- Case 6 ' iTextSharp.text.pdf.PRTokeniser.TK_END_ARRAY
- sb.Append(Environment.NewLine)
- 'sb.Append(" ")
- Case 7 ' iTextSharp.text.pdf.PRTokeniser.TK_START_DIC
- '
- Case 8 ' iTextSharp.text.pdf.PRTokeniser.TK_END_DIC
- '
- Case 9 ' iTextSharp.text.pdf.PRTokeniser.TK_REF
- '
- Case 10 ' iTextSharp.text.pdf.PRTokeniser.TK_OTHER
- Select Case tknValue
- Case "TJ"
- sb.Append(" ")
- Case "ET" ', "TD", "Td" , "Tm" , "T*"
- sb.Append(Environment.NewLine)
- End Select
- End Select
- End While
- End If
- Next i
- reader.Close()
- Catch ex As Exception
- MsgBox("Un errore è stato rilvevato in ParePdfText. Errore:" & vbLf & ex.Message)
- Err.Clear()
- Return String.Empty
- End Try
- Return sb.ToString()
- End Function
- Public Sub LeggiTargaEDateDaPdf(ByVal sfileTxtInput As String, ByVal sfilePdfInput As String)
- 'Lettura del file txt sfileTxtInput prodotto dal pdf tramite il metodo ParsePdfText, estrazione e caricamento dei dati nella tabella VISURE_PDF
- 'Il seguente metodo viene richiamato all'interno di un ciclo FOR nel metodo LeggiRinominaPdfByTarga
- Dim FilePdf As FileInfo
- Dim sRiga As String
- Dim sTarga As String
- Dim sId As String
- Dim FileTxt As FileInfo
- FileTxt = New System.IO.FileInfo(sfileTxtInput)
- Dim reader As StreamReader
- Dim readerDate As StreamReader
- sId = FileTxt.Name.Substring(0, FileTxt.Name.LastIndexOf(".").ToString)
- FilePdf = New System.IO.FileInfo(sfilePdfInput)
- Dim text As New StringBuilder()
- reader = My.Computer.FileSystem.OpenTextFileReader(sfileTxtInput)
- readerDate = My.Computer.FileSystem.OpenTextFileReader(sfileTxtInput)
- Try
- 'Inizio lettura dati e creazione query di INSERT
- Dim sqlIns As String = "INSERT INTO " & Tab & " VALUES(@Targa, "
- Dim MyCmdIns As New SqlCommand(sqlIns, CnSql)
- Dim DateTrovate As MatchCollection = Regex.Matches(text.ToString, "[0-9]*/[0-9]*/[0-9]{4}")
- sRiga = reader.ReadLine.TrimStart
- sTarga = Mid(sRiga, 22, 7)
- MyCmdIns.Parameters.Add("@Targa", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Targa").Value = sTarga
- 'Lettura campi scelti e setup sqlCmd
- Dim telaioInizio As Integer
- Dim telaioFine As Integer
- Dim telaio As String
- telaioInizio = sRiga.IndexOf("Telaio") + 6
- telaioFine = sRiga.IndexOf("Fabbrica / Tipo")
- telaio = sRiga.Substring(telaioInizio, telaioFine - telaioInizio)
- sqlIns = sqlIns & "@Telaio, "
- MyCmdIns.Parameters.Add("@Telaio", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Telaio").Value = telaio
- Dim produttoreInizio As Integer
- Dim produttoreFine As Integer
- Dim produttore As String
- produttoreInizio = sRiga.IndexOf("Fabbrica / Tipo") + 15
- produttoreFine = sRiga.IndexOf("Data Immatricolazione")
- produttore = sRiga.Substring(produttoreInizio, produttoreFine - produttoreInizio)
- sqlIns = sqlIns & "@Produttore, "
- MyCmdIns.Parameters.Add("@Produttore", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Produttore").Value = produttore
- Dim immatricolazioneInizio As Integer
- Dim immatricolazione As String
- immatricolazioneInizio = sRiga.IndexOf("Data Immatricolazione") + Len("Data Immatricolazione")
- immatricolazione = sRiga.Substring(immatricolazioneInizio, 10)
- sqlIns = sqlIns & "@DataImmatricolazione, "
- MyCmdIns.Parameters.Add("@DataImmatricolazione", SqlDbType.SmallDateTime)
- MyCmdIns.Parameters("@DataImmatricolazione").Value = Convert.ToDateTime(immatricolazione.Replace("#", ""))
- Dim cartaInizio As Integer
- Dim carta As String
- cartaInizio = sRiga.IndexOf("Data Aggiornamento Carta Circolazione") + Len("Data Aggiornamento Carta Circolazione")
- carta = sRiga.Substring(cartaInizio, 10)
- sqlIns = sqlIns & "@DataCartaCircolazione, "
- MyCmdIns.Parameters.Add("@DataCartaCircolazione", SqlDbType.SmallDateTime)
- MyCmdIns.Parameters("@DataCartaCircolazione").Value = Convert.ToDateTime(carta)
- Dim kwInizio As Integer
- Dim kwFine As Integer
- Dim kw As String
- kwInizio = sRiga.IndexOf("KW") + 2
- kwFine = sRiga.IndexOf("Classe / Uso")
- kw = sRiga.Substring(kwInizio, kwFine - kwInizio)
- sqlIns = sqlIns & "@KW, "
- MyCmdIns.Parameters.Add("@KW", SqlDbType.Decimal)
- MyCmdIns.Parameters("@KW").Value = Convert.ToDecimal(kw.Replace(",", "."))
- Dim classeInizio As Integer
- Dim classeFine As Integer
- Dim classe As String
- classeInizio = sRiga.IndexOf("Classe / Uso") + 12
- classeFine = sRiga.IndexOf("Carrozzeria")
- classe = sRiga.Substring(classeInizio, classeFine - classeInizio)
- sqlIns = sqlIns & "@Classe, "
- MyCmdIns.Parameters.Add("@Classe", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Classe").Value = classe
- Dim cilindrataInizio As Integer
- Dim cilindrataFine As Integer
- Dim cilindrata As String
- cilindrataInizio = sRiga.IndexOf("Cilindrata") + 10
- cilindrataFine = sRiga.IndexOf("Alimentazione")
- cilindrata = sRiga.Substring(cilindrataInizio, cilindrataFine - cilindrataInizio)
- sqlIns = sqlIns & "@Cilindrata, "
- MyCmdIns.Parameters.Add("@Cilindrata", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Cilindrata").Value = cilindrata
- Dim alimentazioneInizio As Integer
- Dim alimentazioneFine As Integer
- Dim alimentazione As String
- alimentazioneInizio = sRiga.IndexOf("Alimentazione") + 13
- alimentazioneFine = sRiga.IndexOf("Tara")
- alimentazione = sRiga.Substring(alimentazioneInizio, alimentazioneFine - alimentazioneInizio)
- sqlIns = sqlIns & "@Alimentazione, "
- MyCmdIns.Parameters.Add("@Alimentazione", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Alimentazione").Value = alimentazione
- Dim taraInizio As Integer
- Dim taraFine As Integer
- Dim tara As String
- taraInizio = sRiga.IndexOf("Tara") + 4
- taraFine = sRiga.IndexOf("Portata")
- tara = sRiga.Substring(taraInizio, taraFine - taraInizio)
- sqlIns = sqlIns & "@Tara, "
- MyCmdIns.Parameters.Add("@Tara", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Tara").Value = tara
- Dim postiInizio As Integer
- Dim postiFine As Integer
- Dim posti As String
- postiInizio = sRiga.IndexOf("Posti n.ro") + 10
- postiFine = sRiga.IndexOf("Assi n.ro")
- posti = sRiga.Substring(postiInizio, postiFine - postiInizio)
- sqlIns = sqlIns & "@Posti, "
- MyCmdIns.Parameters.Add("@Posti", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Posti").Value = posti
- Dim assiInizio As Integer
- Dim assiFine As Integer
- Dim assi As String
- assiInizio = sRiga.IndexOf("Assi n.ro") + 9
- assiFine = sRiga.IndexOf("Prima Formalita'")
- assi = sRiga.Substring(assiInizio, assiFine - assiInizio)
- sqlIns = sqlIns & "@Assi, "
- MyCmdIns.Parameters.Add("@Assi", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Assi").Value = assi
- Dim primaFormalitaInizio As Integer
- Dim primaFormalitaFine As Integer
- Dim primaFormalita As String
- primaFormalitaInizio = sRiga.IndexOf("Prima Formalita'") + 16
- primaFormalitaFine = sRiga.IndexOf("Data Prima Formalita'")
- primaFormalita = sRiga.Substring(primaFormalitaInizio, primaFormalitaFine - primaFormalitaInizio)
- sqlIns = sqlIns & "@PrimaFomalita, "
- MyCmdIns.Parameters.Add("@PrimaFomalita", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@PrimaFomalita").Value = primaFormalita
- Dim dataPrimaFormalitaInizio As Integer
- Dim dataPrimaFormalita As String
- dataPrimaFormalitaInizio = sRiga.IndexOf("Data Prima Formalita'") + 21
- dataPrimaFormalita = sRiga.Substring(dataPrimaFormalitaInizio, 10)
- sqlIns = sqlIns & "@DataPrimaFormalita, "
- MyCmdIns.Parameters.Add("@DataPrimaFormalita", SqlDbType.SmallDateTime)
- MyCmdIns.Parameters("@DataPrimaFormalita").Value = Convert.ToDateTime(dataPrimaFormalita)
- Dim iultimaforminizio As Integer
- Dim iultimaformfine As Integer
- Dim sFormalita As String
- iultimaforminizio = sRiga.IndexOf("Ultima Formalita'") + 17
- iultimaformfine = sRiga.IndexOf("Data Ultima Formalita'")
- sFormalita = sRiga.Substring(iultimaforminizio, iultimaformfine - iultimaforminizio)
- sqlIns = sqlIns & "@UltimaFormalita, "
- MyCmdIns.Parameters.Add("@UltimaFormalita", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@UltimaFormalita").Value = sFormalita
- Dim sDataUltForm As String
- Dim sDataUltFormInizio As Integer
- sDataUltFormInizio = sRiga.IndexOf("Data Ultima Formalita'") + 22
- sDataUltForm = sRiga.Substring(sDataUltFormInizio, 10)
- sqlIns = sqlIns & "@DataUltimaFormalita, "
- MyCmdIns.Parameters.Add("@DataUltimaFormalita", SqlDbType.SmallDateTime)
- MyCmdIns.Parameters("@DataUltimaFormalita").Value = Convert.ToDateTime(sDataUltForm)
- Dim attoInizio As Integer
- Dim attoFine As Integer
- Dim atto As String
- attoInizio = sRiga.IndexOf("Atto") + 4
- attoFine = sRiga.IndexOf("Data Atto")
- atto = sRiga.Substring(attoInizio, attoFine - attoInizio)
- sqlIns = sqlIns & "@Atto, "
- MyCmdIns.Parameters.Add("@Atto", SqlDbType.NVarChar)
- MyCmdIns.Parameters("@Atto").Value = atto
- Dim dataAttoInizio As Integer
- Dim dataAtto As String
- dataAttoInizio = sRiga.IndexOf("Data Atto") + 9
- dataAtto = sRiga.Substring(dataAttoInizio, 10)
- sqlIns = sqlIns & "@DataAtto, "
- MyCmdIns.Parameters.Add("@DataAtto", SqlDbType.SmallDateTime)
- MyCmdIns.Parameters("@DataAtto").Value = Convert.ToDateTime(dataAtto)
- Dim prezzoVeicoloInizio As Integer
- Dim prezzoVeicoloFine As Integer
- Dim prezzoVeicolo As String
- prezzoVeicoloInizio = sRiga.IndexOf("Prezzo del Veicolo") + 18
- prezzoVeicoloFine = sRiga.IndexOf("Proprietario")
- prezzoVeicolo = sRiga.Substring(prezzoVeicoloInizio, prezzoVeicoloFine - prezzoVeicoloInizio).Replace("*", "").Replace(".", "").Replace(",", ".").Replace(" ", "").ToUpper.Replace("EURO", "")
- sqlIns = sqlIns & "@PrezzoVeicolo, "
- MyCmdIns.Parameters.Add("@PrezzoVeicolo", SqlDbType.Decimal)
- MyCmdIns.Parameters("@PrezzoVeicolo").Value = Convert.ToDecimal(prezzoVeicolo.Substring(0, prezzoVeicolo.Length - 3))
- 'Completamento della stringa per la query di INSERT in VISURE_PDF.
- sqlIns = sqlIns.Substring(0, sqlIns.Length - 2)
- sqlIns = sqlIns & ")"
- 'Esecuzione Query di insert
- MyCmdIns.CommandText = sqlIns
- MyCmdIns.CommandTimeout = 0
- MyCmdIns.CommandType = CommandType.Text
- MyCmdIns.ExecuteNonQuery()
- 'Inizio gestione del blocco proprietari.
- Dim counter As Integer = 0
- MyCmdIns = New SqlCommand(sqlIns, CnSql)
- 'Ridimensionamento sRiga al blocco proprietario.
- sRiga = sRiga.Substring(sRiga.IndexOf("Proprietario"), sRiga.IndexOf("ANNOTAZIONI") - sRiga.IndexOf("Proprietario"))
- 'Conto n proprietari.
- For Each dato As Match In Regex.Matches(sRiga, "Proprietario")
- counter += 1
- Next
- nProprietari = counter
- 'Dichiarazione array di indici blocco proprietario.
- Dim indexProprietario(counter) As Integer
- Dim indexTipo(counter) As Integer
- Dim indexDataNascita(counter) As Integer
- Dim indexComuneNascita(counter) As Integer
- Dim indexComuneResidenza(counter) As Integer
- Dim indexIndirizzo(counter) As Integer
- 'Dichiarazione array blocco proprietario.
- Dim proprietario(counter) As String
- Dim tipo(counter) As String
- Dim nascita(counter) As String
- Dim comuneNascita(counter) As String
- Dim residenza(counter) As String
- Dim indirizzo(counter) As String
- Dim arrCmd(counter) As String
- Dim arrIns(counter) As String
- 'Dichiarazione Parametri SQL
- MyCmdIns.Parameters.Add("@Targa", SqlDbType.NVarChar)
- MyCmdIns.Parameters.Add("@Proprietario", SqlDbType.NVarChar)
- MyCmdIns.Parameters.Add("@Tipo", SqlDbType.NVarChar)
- MyCmdIns.Parameters.Add("@DataNascita", SqlDbType.SmallDateTime)
- MyCmdIns.Parameters.Add("@ComuneNascita", SqlDbType.NVarChar)
- MyCmdIns.Parameters.Add("@ComuneResidenza", SqlDbType.NVarChar)
- MyCmdIns.Parameters.Add("@Indirizzo", SqlDbType.NVarChar)
- 'Inizio salvataggio indici delle informazioni da estrarre relative al blocco proprietari
- 'Gli indici verranno utilizzati per indicare il punto di inizio e di fine del dato da estrarre
- counter = 0
- For Each dato As Match In Regex.Matches(sRiga, "Proprietario")
- indexProprietario(counter) = dato.Index
- counter += 1
- Next
- counter = 0
- 'Sesso / Tipo Società
- For Each dato As Match In Regex.Matches(sRiga, "Sesso / Tipo Societa'")
- indexTipo(counter) = dato.Index
- counter += 1
- Next
- counter = 0
- 'Data di nascita
- For Each dato As Match In Regex.Matches(sRiga, "Data di nascita")
- indexDataNascita(counter) = dato.Index
- counter += 1
- Next
- counter = 0
- 'Comune di nascita
- For Each dato As Match In Regex.Matches(sRiga, "Comune di nascita")
- indexComuneNascita(counter) = dato.Index
- counter += 1
- Next
- counter = 0
- 'Comune di residenza
- For Each dato As Match In Regex.Matches(sRiga, "Comune di residenza")
- indexComuneResidenza(counter) = dato.Index
- counter += 1
- Next
- counter = 0
- 'Indirizzo
- For Each dato As Match In Regex.Matches(sRiga, "Indirizzo")
- indexIndirizzo(counter) = dato.Index
- counter += 1
- Next
- counter = 0
- 'Estrazione blocco proprietario da PDF utilizzando gli indici appena salvati.
- 'Creazione ed inizializzazione parametri sql per l'insert nella tabella Anagrafica
- For Each dato As Match In Regex.Matches(sRiga, "Proprietario")
- sqlIns = "INSERT INTO Anagrafica VALUES(@Targa, "
- 'Targa_FK
- MyCmdIns.Parameters("@Targa").Value = sTarga
- 'Proprietario
- proprietario(counter) = sRiga.Substring(indexProprietario(counter) + Len("Proprietario"), indexTipo(counter) - (indexProprietario(counter) + Len("Proprietario")))
- arrCmd(counter) = "Proprietario nvarchar(100) NULL, "
- arrIns(counter) = "@Proprietario, "
- MyCmdIns.Parameters("@Proprietario").Value = proprietario(counter)
- sqlIns = sqlIns & arrIns(counter)
- 'Sesso / Tipo Società
- tipo(counter) = sRiga.Substring(indexTipo(counter) + Len("Sesso / Tipo Societa'"), indexDataNascita(counter) - (indexTipo(counter) + Len("Sesso / Tipo Societa'")))
- arrCmd(counter) = "Tipo nvarchar(100) NULL, "
- arrIns(counter) = "@Tipo, "
- MyCmdIns.Parameters("@Tipo").Value = tipo(counter)
- sqlIns = sqlIns & arrIns(counter)
- 'Data di Nascita
- nascita(counter) = sRiga.Substring(indexDataNascita(counter) + Len("Data di nascita"), 10)
- arrCmd(counter) = "DataNascita smalldatetime NULL, "
- arrIns(counter) = "@DataNascita, "
- MyCmdIns.Parameters("@DataNascita").Value = Convert.ToDateTime(nascita(counter))
- sqlIns = sqlIns & arrIns(counter)
- 'Comune di Nascita
- comuneNascita(counter) = sRiga.Substring(indexComuneNascita(counter) + Len("Comune di nascita"), indexComuneResidenza(counter) - (indexComuneNascita(counter) + Len("Comune di nascita")))
- arrCmd(counter) = "ComuneNascita nvarchar(100) NULL, "
- arrIns(counter) = "@ComuneNascita, "
- MyCmdIns.Parameters("@ComuneNascita").Value = comuneNascita(counter)
- sqlIns = sqlIns & arrIns(counter)
- 'Comune di Residenza
- residenza(counter) = sRiga.Substring(indexComuneResidenza(counter) + Len("Comune di residenza"), indexIndirizzo(counter) - (indexComuneResidenza(counter) + Len("Comune di residenza")))
- arrCmd(counter) = "ComuneResidenza nvarchar(100) NULL, "
- arrIns(counter) = "@ComuneResidenza, "
- MyCmdIns.Parameters("@ComuneResidenza").Value = residenza(counter)
- sqlIns = sqlIns & arrIns(counter)
- 'Indirizzo
- If counter = 0 And nProprietari <> 1 Then
- indirizzo(counter) = sRiga.Substring(indexIndirizzo(counter) + Len("Indirizzo"), indexProprietario(counter + 1) - (indexIndirizzo(counter) + Len("Indirizzo")))
- Else
- indirizzo(counter) = sRiga.Substring(indexIndirizzo(counter) + Len("Indirizzo"), sRiga.Length() - (indexIndirizzo(counter) + Len("Indirizzo")))
- End If
- arrIns(counter) = "@Indirizzo, "
- MyCmdIns.Parameters("@Indirizzo").Value = indirizzo(counter)
- sqlIns = sqlIns & arrIns(counter)
- 'Chiusura Select / Insert
- sqlIns = sqlIns.Substring(0, sqlIns.Length - 2) & ")"
- MyCmdIns.CommandText = sqlIns
- MyCmdIns.CommandTimeout = 0
- MyCmdIns.CommandType = CommandType.Text
- MyCmdIns.ExecuteNonQuery()
- counter += 1
- Next
- 'Cancellazione record duplicati dalla tabella Anagrafica
- Dim sqlStr As String = "DELETE FROM Anagrafica WHERE ID NOT IN (SELECT MAX(ID) FROM Anagrafica GROUP BY Targa_FK, Proprietario HAVING MAX(ID) IS NOT NULL)"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlCommand(sqlStr, myConn)
- myCmd.ExecuteNonQuery()
- End Using
- myConn.Close()
- End Using
- reader.Close()
- readerDate.Close()
- 'Elimina il file txt analizzato
- FileTxt.Delete()
- Catch ex As Exception
- 'Incremento valore errori e pulizia file txt utilizzato
- errors += 1
- reader.Close()
- readerDate.Close()
- FileTxt.Delete()
- Err.Clear()
- End Try
- End Sub
- Public Shared Function CnSqlOpen(ByVal connectionString As String) As Boolean
- 'Funzione utilizzata per l'apertura di una connessione con il DB. connectionString recuperata dal file .config
- Try
- If (CnSql Is Nothing) Then
- CnSql = New SqlConnection(connectionString)
- CnSql.Open()
- Return True
- End If
- If (CnSql.State = ConnectionState.Open) Then
- Return True
- End If
- CnSql = New SqlConnection(connectionString)
- CnSql.Open()
- Return True
- Catch ex As Exception
- MsgBox("Un errore è stato rilevato in CnSqlOpen. Errore:" & vbLf & ex.Message)
- End Try
- End Function
- Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- 'Caricamento del Programma. Inizializzazione variabili globali dell'operatore e registrazione degli annessi Log nella tabella LOG_Operazioni.
- ProgressBar1.Visible = False
- GetUserName()
- User.Text = "Benvenuto " & G_ACCOUNTWINDOWS & "."
- RegistraLog("Apertura programma Visure_Pdf_Excel", "NULL")
- 'Setup delle checkbox
- Try
- SaveExcelButton.Visible = False
- Targa.Checked = True
- SessoTipoSocieta.Enabled = False
- DataNascita.Enabled = False
- Comune.Enabled = False
- Residenza.Enabled = False
- Indirizzo.Enabled = False
- Catch ex As Exception
- MsgBox("Un errore è stato rilevato durante il caricamento del programma. Errore:" & vbLf & ex.Message)
- End Try
- End Sub
- Private Sub FormDisposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
- 'Chiusura del programma, richiamo Garbage Collector per il rilascio di tutte le risorse utilizzate.
- 'Registrazione dei Log nella tabella LOG_Operazioni.
- GC.Collect()
- GC.WaitForPendingFinalizers()
- RegistraLog("Chiusura programma Visure_Pdf_Excel", "NULL")
- End Sub
- Private Sub UP_Excel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UP_Excel.Click
- 'Selezione del file Excel, Registrazione Log.
- 'Stampa feedback sulla maschera per notificare l'utente del corretto caricamento.
- fileExcel = ""
- 'upload file
- Try
- Excel_Check.ForeColor = Color.Green
- Excel_Check.Text = ""
- OpenFileExcel.InitialDirectory = "C:\"
- OpenFileExcel.Filter = "File Excel|*.xls; *.xlsx"
- If OpenFileExcel.ShowDialog = DialogResult.OK Then
- fileExcel = OpenFileExcel.FileName
- Excel_Check.Text = "File selezionato correttamente."
- Excel_TextBox.Text = fileExcel
- RegistraLog("Selezionato file Excel: " & Path.GetFileName(fileExcel), "NULL")
- Else
- Excel_Check.ForeColor = Color.Red
- Excel_Check.Text = "Impossibile selezionare il file."
- Exit Sub
- End If
- Catch ex As Exception
- MsgBox("Un errore è stato rilevato durante il caricamento del file Excel. Errore:" & vbLf & ex.Message)
- Err.Clear()
- End Try
- End Sub
- Private Sub UP_Pdf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UP_Pdf.Click
- 'Selezione del file Excel, Registrazione Log.
- 'Stampa feedback sulla maschera per notificare l'utente del corretto caricamento.
- DirPdf = ""
- 'upload file
- Try
- Pdf_Check.ForeColor = Color.Green
- Pdf_Check.Text = ""
- If OpenDirPdf.ShowDialog = DialogResult.OK Then
- DirPdf = OpenDirPdf.SelectedPath
- Pdf_Check.Text = "Cartella selezionata correttamente."
- PDF_TextBox.Text = DirPdf
- RegistraLog("Selezionata cartella PDF: " & Path.GetFileName(DirPdf), "NULL")
- Else
- Pdf_Check.ForeColor = Color.Red
- Pdf_Check.Text = "Impossibile selezionare la cartella."
- Exit Sub
- End If
- Catch ex As Exception
- MsgBox("Un errore è stato rilevato durante il caricamento del file PDF. Errore:" & vbLf & ex.Message)
- Err.Clear()
- End Try
- End Sub
- Private Sub ExcelManagment(ByVal filePath As String)
- 'Lettura file Excel tramite il parametro filePath e salvataggio dei relativi dati nella data table DtTab
- 'Creazione SELECT per associare i dati estratti dal PDF contenuti nella tabella VISURE_PDF con le targhe presenti nella tabella TempTabXLS
- 'Oggetti DB utilizzati: VISURE_PDF, TempTabXLS, Anagrafica
- Try
- Dim sFileName As String = filePath
- Dim MyConnection As OleDbConnection
- Dim DtTab As New System.Data.DataTable
- Dim sTipoFile As String
- ProgressBar1.Step = 10
- 'Individuo il tipo di file Excel scelto
- If IO.Path.GetExtension(sFileName.ToUpper) = ".XLS" Then
- sTipoFile = "Excel 8.0"
- MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & sFileName & "';Extended Properties=" & sTipoFile & ";")
- Else
- sTipoFile = "Excel 12.0"
- MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sFileName & "';Extended Properties=" & sTipoFile & ";")
- End If
- ProgressBar1.PerformStep()
- ' Apre connessione con Excel
- MyConnection.Open()
- 'Popola data table
- Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
- Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
- MyCommand.TableMappings.Add("Table", " ")
- ProgressBar1.PerformStep()
- MyCommand.Fill(DtTab)
- MyConnection.Close()
- 'Creazione tabella temporanea TempTabXLS
- CreateTable(TempTab, DtTab)
- MsgBox("File excel elaborato correttamente. Inizio elaborazione file PDF.")
- 'Caricamento DataTable in TempTabXLS
- DataTableToSql(DtTab)
- 'Creazione Select in base ai campi selzionati per l'associazione dati Excel/PDF.
- 'Creazione Insert dei dati nella tabella Dettagli.
- 'N.B. Tutti i dati saranno inseriti nella tabella Dettagli indifferentemente dai campi scelti.
- 'N.B. Tutti i dati estratti sono presenti sul DB. Solo i campi selezionati verranno estratti dalla query.
- Dim sqlCmd As String = "SELECT "
- Dim sqlDettagli As String = "SELECT " & TempTab & ".Targa, "
- For i = 0 To indexColTempTab
- sqlCmd = sqlCmd & TempTab & "." & TempTabColName(i) & " as '" & TempTabColName(i).Replace("_", " ") & "', "
- Next
- If Telaio.Checked Then
- sqlCmd = sqlCmd & "Telaio, "
- End If
- sqlDettagli = sqlDettagli & "Telaio, "
- If Produttore.Checked Then
- sqlCmd = sqlCmd & "Produttore, "
- End If
- sqlDettagli = sqlDettagli & "Produttore, "
- If Immatricolazione.Checked Then
- sqlCmd = sqlCmd & "DataImmatricolazione as 'Data di Immatricolazione', "
- End If
- sqlDettagli = sqlDettagli & "DataImmatricolazione as 'Data di Immatricolazione', "
- If CartaDiCircolazione.Checked Then
- sqlCmd = sqlCmd & "DataCartaCircolazione as 'Data Aggiornamento Carta di Circolazione', "
- End If
- sqlDettagli = sqlDettagli & "DataCartaCircolazione as 'Data Aggiornamento Carta di Circolazione', "
- If KW.Checked Then
- sqlCmd = sqlCmd & "KW, "
- End If
- sqlDettagli = sqlDettagli & "KW, "
- If Classe.Checked Then
- sqlCmd = sqlCmd & "Classe as 'Classe/Uso', "
- End If
- sqlDettagli = sqlDettagli & "Classe as 'Classe/Uso', "
- If Cilindrata.Checked Then
- sqlCmd = sqlCmd & "Cilindrata, "
- End If
- sqlDettagli = sqlDettagli & "Cilindrata, "
- If Alimentazione.Checked Then
- sqlCmd = sqlCmd & "Alimentazione, "
- End If
- sqlDettagli = sqlDettagli & "Alimentazione, "
- If Tara.Checked Then
- sqlCmd = sqlCmd & "Tara, "
- End If
- sqlDettagli = sqlDettagli & "Tara, "
- If Posti.Checked Then
- sqlCmd = sqlCmd & "Posti as 'Posti n.ro', "
- End If
- sqlDettagli = sqlDettagli & "Posti as 'Posti n.ro', "
- If Assi.Checked Then
- sqlCmd = sqlCmd & "Assi as 'Assi n.ro', "
- End If
- sqlDettagli = sqlDettagli & "Assi as 'Assi n.ro', "
- If PrimaFormalita.Checked Then
- sqlCmd = sqlCmd & "PrimaFormalita as 'Prima Formalità', "
- End If
- sqlDettagli = sqlDettagli & "PrimaFormalita as 'Prima Formalità', "
- If DataPrimaFormalita.Checked Then
- sqlCmd = sqlCmd & "DataPrimaFormalita as 'Data Prima Formalità', "
- End If
- sqlDettagli = sqlDettagli & "DataPrimaFormalita as 'Data Prima Formalità', "
- If UltimaFormalita.Checked Then
- sqlCmd = sqlCmd & "UltimaFormalita as 'Ultima Formalità', "
- End If
- sqlDettagli = sqlDettagli & "UltimaFormalita as 'Ultima Formalità', "
- If DataUltimaFormalita.Checked Then
- sqlCmd = sqlCmd & "DataUltimaFormalita as 'Data Ultima Formalità', "
- End If
- sqlDettagli = sqlDettagli & "DataUltimaFormalita as 'Data Ultima Formalità', "
- If Atto.Checked Then
- sqlCmd = sqlCmd & "Atto, "
- End If
- sqlDettagli = sqlDettagli & "Atto, "
- If DataAtto.Checked Then
- sqlCmd = sqlCmd & "DataAtto as 'Data Atto', "
- End If
- sqlDettagli = sqlDettagli & "DataAtto as 'Data Atto', "
- If PrezzoVeicolo.Checked Then
- sqlCmd = sqlCmd & "PrezzoVeicolo as 'Prezzo del Veicolo', "
- End If
- sqlDettagli = sqlDettagli & "PrezzoVeicolo as 'Prezzo del Veicolo', "
- If Proprietario.Checked Then
- sqlCmd = sqlCmd & "Proprietario, "
- End If
- If SessoTipoSocieta.Checked Then
- sqlCmd = sqlCmd & "Tipo as 'Sesso/Tipo Società', "
- End If
- If DataNascita.Checked Then
- sqlCmd = sqlCmd & "DataNascita as 'Data di Nascita', "
- End If
- If Comune.Checked Then
- sqlCmd = sqlCmd & "ComuneNascita as 'Comune di Nascita', "
- End If
- If Residenza.Checked Then
- sqlCmd = sqlCmd & "ComuneResidenza as 'Comune di Residenza', "
- End If
- If Indirizzo.Checked Then
- sqlCmd = sqlCmd & "Indirizzo as 'Indirizzo di Residenza', "
- End If
- 'Chiusura delle Query.
- sqlCmd = sqlCmd.Substring(0, sqlCmd.Length - 2) & " FROM " & TempTab & ", " & Tab & ", Anagrafica WHERE " & TempTab & ".Targa = " & Tab & ".Targa AND " & Tab & ".Targa = Anagrafica.Targa_FK"
- sqlDettagli = sqlDettagli.Substring(0, sqlDettagli.Length - 2) & " FROM " & TempTab & ", " & Tab & " WHERE " & TempTab & ".Targa = " & Tab & ".Targa"
- 'Creazione DataTable
- Dim RemoteDtTab As New System.Data.DataTable
- 'Apertura connessione al DB
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- 'Popolamento della DataTable contenente i dati da salvare su file Excel
- Using loader As New SqlDataAdapter(sqlCmd, myConn)
- loader.Fill(RemoteDtTab)
- End Using
- 'Popolamento della DataTable contenente i dati da caricare nella tabella Dettagli.
- Using loaderDettagli As New SqlDataAdapter(sqlDettagli, myConn)
- loaderDettagli.Fill(DettagliDtTab)
- End Using
- myConn.Close()
- End Using
- 'Gestione degli errori, conto pdf mancanti.
- Dim pdfMancanti As String = Convert.ToString(ErrorFinder().Rows.Count)
- ProgressBar1.Value = 100
- If ErrorFinder().Rows.Count > 0 Then
- Dim dt As System.Data.DataTable = ErrorFinder() 'Metodo per la ricerca degli errori tramite la discrepanza tra TempTabXLS e VISURE_PDF
- Dim errori As String = ""
- Dim rowIndex As Integer = 0
- For Each dr In dt.Rows
- errori = errori & Convert.ToString(dt.Rows(rowIndex)(0)) & vbLf 'Lista targhe con pdf mancante/corrotto
- rowIndex += 1
- Next
- 'Feedback errori riscontrari e salvataggio dei Log
- MsgBox("Elaborazione PDF completata con " & errors & " errori. " & vbLf & vbLf & "PDF mancanti/corrotti: " & pdfMancanti & "." & vbLf & vbLf & "Targa PDF mancanti/corrotti: " & errori & vbLf & "Inizio salvataggio file Excel.")
- RegistraLog("PDF mancanti/corrotti: " & pdfMancanti, "NULL")
- RegistraLog("Targa PDF mancanti/corrotti: " & errori, "NULL")
- Else
- MsgBox("Elaborazione PDF completata con " & errors & " errori. " & vbLf & vbLf & "PDF mancanti/corrotti: " & pdfMancanti & "." & vbLf & vbLf & "Inizio salvataggio file Excel.")
- End If
- ProgressBar1.Value = 0
- 'Inizio scrittura dei dati sul file Excel del Cliente.
- Dim strFilePath As String = filePath.Replace(Path.GetFileName(filePath), "")
- ExcelExport(RemoteDtTab, strFilePath, True)
- Catch ex As Exception
- MsgBox("Un errore è stato rilevato durante l'elaborazione dei dati. Errore:" & vbLf & ex.Message)
- RegistraLog("Interruzione programma Visure_Pdf_Excel a causa di un errore.", "NULL")
- ProgressBar1.Value = 0
- Err.Clear()
- Exit Sub
- End Try
- End Sub
- Private Sub ExcelExport(ByVal ExportDataTable As DataTable, ByVal filePath As String, ByVal ScegliExcel As Boolean)
- 'Scrittura dei dati estratti dal pdf sul file Excel del Cliente
- 'I dati estratti dal pdf sono contenuti in ExportDataTable.
- 'Il file Excel viene individuato dal metodo tramite il parametro filePath
- Dim excel As New Microsoft.Office.Interop.Excel.Application
- Dim wBook As Microsoft.Office.Interop.Excel.Workbook
- Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
- Try
- ProgressBar1.Value = 0
- ProgressBar1.Step = 1
- ProgressBar1.PerformStep()
- 'Dichiarazione variabili
- If ScegliExcel Then
- wBook = excel.Workbooks.Open(fileExcel)
- Else
- wBook = excel.Workbooks.Add()
- End If
- wSheet = wBook.ActiveSheet()
- Dim dt As System.Data.DataTable = ExportDataTable
- Dim dc As System.Data.DataColumn
- Dim dr As System.Data.DataRow
- Dim colIndex As Integer = 0
- Dim rowIndex As Integer = 0
- Dim Counter As Integer = 0
- Dim indexProprietario As Integer
- Dim indexTipo As Integer
- Dim indexDataN As Integer
- Dim indexComuneN As Integer
- Dim indexComuneRes As Integer
- Dim indexIndirizzo As Integer
- 'Scrittura header e salvataggio index blocco proprietari
- For Each dc In dt.Columns
- colIndex = colIndex + 1
- excel.Cells(1, colIndex) = dc.ColumnName
- If dc.ColumnName = "Proprietario" Then
- indexProprietario = colIndex
- End If
- If dc.ColumnName = "Sesso/Tipo Società" Then
- indexTipo = colIndex
- End If
- If dc.ColumnName = "Data di Nascita" Then
- indexDataN = colIndex
- End If
- If dc.ColumnName = "Comune di Nascita" Then
- indexComuneN = colIndex
- End If
- If dc.ColumnName = "Comune di Residenza" Then
- indexComuneRes = colIndex
- End If
- If dc.ColumnName = "Indirizzo di Residenza" Then
- indexIndirizzo = colIndex
- End If
- Next
- 'Scrittura dei dati sul file Excel
- For Each dr In dt.Rows
- rowIndex += 1
- colIndex = 0
- Counter += 1
- If Counter Mod 10 = 0 Then
- ProgressBar1.PerformStep()
- End If
- For Each dc In dt.Columns
- colIndex += 1
- excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
- Next
- Next
- ProgressBar1.Step = 1
- Dim lastRow As Integer = wSheet.UsedRange.Columns.Count()
- 'Unione proprietari multipli
- If Proprietario.Checked Then
- 'Eliminazione righe doppia ed aggiunta delle colonne necessarie per i proprietari multipli.
- rowIndex = 0
- Dim colCopyIndex As Integer
- Dim proprColRange As Integer
- For Each dr In dt.Rows
- rowIndex += 1
- colCopyIndex = indexProprietario
- If wSheet.Cells(rowIndex, 1).Value = wSheet.Cells(rowIndex + 1, 1).Value Then
- If rowIndex Mod 5 = 0 Then
- ProgressBar1.PerformStep()
- End If
- proprColRange = lastRow - indexProprietario
- For colIndex = lastRow + 1 To lastRow + proprColRange + 1
- wSheet.Cells(rowIndex, colIndex).Value = wSheet.Cells(rowIndex + 1, colCopyIndex).Value
- colCopyIndex += 1
- Next
- wSheet.Rows(rowIndex + 1).Delete()
- End If
- Next
- End If
- 'Scrittura header secondo Proprietario
- Dim contaUltimaColonna As Integer
- contaUltimaColonna = lastRow
- If Proprietario.Checked Then
- wSheet.Cells(1, contaUltimaColonna + 1).Value = "Secondo Proprietario"
- contaUltimaColonna += 1
- End If
- If SessoTipoSocieta.Checked Then
- wSheet.Cells(1, contaUltimaColonna + 1).Value = "Sesso/Tipo Scoietà S.P."
- contaUltimaColonna += 1
- End If
- If DataNascita.Checked Then
- wSheet.Cells(1, contaUltimaColonna + 1).Value = "Data di Nascita S.P."
- contaUltimaColonna += 1
- End If
- If Comune.Checked Then
- wSheet.Cells(1, contaUltimaColonna + 1).Value = "Comune di Residenza S.P."
- contaUltimaColonna += 1
- End If
- If Residenza.Checked Then
- wSheet.Cells(1, contaUltimaColonna + 1).Value = "Comune di Nascita S.P."
- contaUltimaColonna += 1
- End If
- If Indirizzo.Checked Then
- wSheet.Cells(1, contaUltimaColonna + 1).Value = "Indirizzo di Residenza S.P."
- contaUltimaColonna += 1
- End If
- If ScegliExcel Then
- 'Formattazione dati aggiunti al file del Cliente per permettere una lettura del file facilitata.
- wSheet.UsedRange.Borders.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
- wSheet.UsedRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
- wSheet.UsedRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
- wSheet.Columns.AutoFit()
- ProgressBar1.Step = 5
- ProgressBar1.PerformStep()
- 'Controllo esistenza file ed eliminazione file vecchio.
- Dim strFileName = filePath & Tab & ".xlsx"
- If System.IO.File.Exists(strFileName) Then
- ProgressBar1.PerformStep()
- System.IO.File.Delete(strFileName)
- End If
- 'Creazione percorso per il salvataggio del file.
- CreaCartellaPercorso()
- strFileName = fileExcel.Replace(Path.GetFileName(fileExcel), "VISURE_PDF.xlsx")
- 'Salvataggio file.
- ProgressBar1.PerformStep()
- wBook.SaveAs(strFileName)
- wBook.Close()
- ProgressBar1.PerformStep()
- excel.Quit()
- ProgressBar1.Value = 100
- 'Feedback salvataggio riuscito e registrazione Log.
- MsgBox("File " & Path.GetFileName(strFileName) & " è stato salvato correttamente in " & strFileName)
- ProgressBar1.Value = 0
- ProgressBar1.Visible = False
- InserisciTestata()
- DettagliToSql(DettagliDtTab)
- RegistraLog("Salvataggio file excel elaborato: " & Path.GetFileName(strFileName), "NULL")
- 'Richiesta nuova elaborazione
- Dim result As DialogResult = Windows.Forms.DialogResult.No
- GC.Collect()
- GC.WaitForPendingFinalizers()
- result = MessageBox.Show("Vuoi continuare con un'altra elaborazione?", "Leggi visure da pdf", MessageBoxButtons.YesNo)
- If result = Windows.Forms.DialogResult.Yes Then
- TableDeleter(TempTab)
- Excel_Check.Visible = False
- Pdf_Check.Visible = False
- Excel_TextBox.Text = ""
- PDF_TextBox.Text = ""
- Else
- TableDeleter(TempTab)
- Me.Close()
- End If
- Else
- wSheet.UsedRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
- wSheet.Columns.AutoFit()
- excel.Visible = True
- End If
- TableDeleter(TempTab)
- GC.Collect()
- GC.WaitForPendingFinalizers()
- Catch ex As Exception
- 'Gestione degli errori. Eliminazione tabella temporanea e registrazione dei Log
- TableDeleter(TempTab)
- GC.Collect()
- GC.WaitForPendingFinalizers()
- MsgBox("Un errore è stato rilevato durante il salvataggio dei risultati. Errore:" & vbLf & ex.Message)
- RegistraLog("Interruzione programma Visure_Pdf_Excel a causa di un errore.", "NULL")
- excel.Quit()
- ProgressBar1.Value = 0
- Err.Clear()
- End Try
- End Sub
- Private Sub DataTableToSql(ByVal dt As DataTable)
- 'Inserimento dei dati presenti sul file Excel del Cliente nella tabella temporanea.
- 'I dati presenti sul file Excel del Cliente sono contenuti nella DataTable dt
- Try
- ProgressBar1.Step = 1
- Dim counter As Integer
- Dim progressBarCounter As Integer = 0
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- 'Creazione Insert
- Dim sqlCmd As String = "INSERT INTO " & TempTab & " VALUES( "
- For i = 0 To indexColTempTab
- sqlCmd = sqlCmd & "@" & TempTabColName(i) & ", "
- Next
- sqlCmd = sqlCmd.Substring(0, Len(sqlCmd) - 2) & ")"
- 'Creazione Parametri SQL
- Using myCmd As New SqlCommand(sqlCmd, myConn)
- For i = 0 To indexColTempTab
- myCmd.Parameters.Add("@" & TempTabColName(i), SqlDbType.NVarChar)
- Next
- 'Inizializzazione Parametri ed esecuzioni query
- For Each dr In dt.Rows
- counter = 0
- For Each dc In dt.Columns
- myCmd.Parameters("@" & TempTabColName(counter)).Value = dr(dc.ColumnName)
- counter += 1
- If counter = indexColTempTab + 1 Then
- Exit For
- End If
- progressBarCounter += 1
- If progressBarCounter Mod 20 = 0 Then
- ProgressBar1.PerformStep()
- End If
- Next
- myCmd.ExecuteNonQuery()
- Next
- End Using
- myConn.Close()
- End Using
- ProgressBar1.Value = 100
- Catch ex As Exception
- MsgBox("Un errore è stato rilevato nell'elaborazione del file Excel. Errore:" & vbLf & ex.Message)
- RegistraLog("Interruzione programma Visure_Pdf_Excel a causa di un errore.", "NULL")
- ProgressBar1.Value = 0
- Exit Sub
- End Try
- End Sub
- Private Sub TableDeleter(ByVal tablename As String)
- 'Eliminazione della tabella scelta.
- 'tablename contiene il nome della tabella.
- Try
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlCommand("DROP TABLE " & tablename, myConn)
- myCmd.ExecuteNonQuery()
- End Using
- End Using
- Catch ex As Exception
- Err.Clear()
- End Try
- End Sub
- Private Sub CreateTable(ByVal tableName As String, ByVal dt As DataTable)
- 'Creazione della tabella temporanea TempTabXLS in modo dinamico in base al numero ed al nome di colonne del file Excel.
- 'Unico vincolo la presenza della colonna Targa.
- 'tableName contiene il nome della tabella temporanea (acquisito dal file .config)
- 'DataTable contiene i dati contenuti nel file Excel del Cliente in modo da creare una tabella con lo stesso numero e stesso tipo di colonne.
- Try
- indexColTempTab = 0
- For Each dc In dt.Columns
- TempTabColName(indexColTempTab) = Convert.ToString(dc.ColumnName).Replace(" ", "_").Replace("à", "a").Replace("è", "e").Replace("é", "e").Replace("ì", "i").Replace("ò", "o").Replace("ù", "u")
- If TempTabColName(indexColTempTab).ToLower.Contains("targa") Then
- TempTabColName(indexColTempTab) = "Targa"
- End If
- indexColTempTab += 1
- Next
- indexColTempTab -= 1
- Dim sqlStr As String = "Create Table " & TempTab & "( ID integer IDENTITY(1,1) PRIMARY KEY, "
- For i = 0 To indexColTempTab
- sqlStr = sqlStr & TempTabColName(i) & " nvarchar(100) NULL, "
- Next
- sqlStr = sqlStr.Substring(0, Len(sqlStr) - 2) & ")"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlCommand(sqlStr, myConn)
- myCmd.ExecuteNonQuery()
- End Using
- End Using
- Catch ex As Exception
- Err.Clear()
- Exit Sub
- End Try
- End Sub
- Private Sub Proprietario_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Proprietario.CheckedChanged
- 'Disabilita tutti i campi legati al Proprietario finché il campo proprietario non è spuntato.
- If Proprietario.Checked Then
- SessoTipoSocieta.Enabled = True
- DataNascita.Enabled = True
- Comune.Enabled = True
- Residenza.Enabled = True
- Indirizzo.Enabled = True
- Else
- SessoTipoSocieta.Enabled = False
- DataNascita.Enabled = False
- Comune.Enabled = False
- Residenza.Enabled = False
- Indirizzo.Enabled = False
- SessoTipoSocieta.Checked = False
- DataNascita.Checked = False
- Comune.Checked = False
- Residenza.Checked = False
- Indirizzo.Checked = False
- End If
- End Sub
- Private Sub GetUserName()
- 'Inizializza le variabili globali legati all'operatore.
- 'Inserisce i dati nella tabella TB_OPERATORI in caso non fossero presenti.
- 'Esegue una update del record relativo all'operatore nel caso i dati fossero mancanti.
- Try
- Dim userFullName As String = UserPrincipal.Current.DisplayName
- G_USERFULLNAME = userFullName
- If TypeOf My.User.CurrentPrincipal Is Security.Principal.WindowsPrincipal Then
- Dim parts() As String = Split(My.User.Name, "\")
- Dim username As String = parts(1)
- G_ACCOUNTWINDOWS = username
- Try
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Dim sqlStr As String = "Select idOperatore From TB_OPERATORI WHERE AccountWindows = '" & username & "'"
- Using myCmd As New SqlDataAdapter(sqlStr, myConn)
- Dim dt As New System.Data.DataTable
- myCmd.Fill(dt)
- G_IDOPERATORE = Convert.ToString(dt.Rows(0)(0))
- End Using 'End Select Using
- sqlStr = "UPDATE TB_OPERATORI SET UserName = '" & username & "' WHERE AccountWindows = '" & username & "'"
- Using myCmd As New SqlCommand(sqlStr, myConn)
- myCmd.ExecuteNonQuery()
- End Using 'End Update Using
- myConn.Close()
- End Using 'End myConn Using
- Catch ex As Exception
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Dim sqlStr As String = "INSERT INTO TB_OPERATORI VALUES(@Operatore, NULL, NULL, @Username, NULL, 0, 0, 0, NULL, @Username)"
- Using myCmd As New SqlCommand(sqlStr, myConn)
- myCmd.Parameters.Add("@Operatore", SqlDbType.VarChar)
- myCmd.Parameters("@Operatore").Value = G_USERFULLNAME
- myCmd.Parameters.Add("@Username", SqlDbType.VarChar)
- myCmd.Parameters("@Username").Value = username
- myCmd.ExecuteNonQuery()
- End Using
- sqlStr = "Select idOperatore From TB_OPERATORI WHERE AccountWindows = '" & username & "'"
- Using myCmd As New SqlDataAdapter(sqlStr, myConn)
- Dim dt As New System.Data.DataTable
- myCmd.Fill(dt)
- G_IDOPERATORE = Convert.ToString(dt.Rows(0)(0))
- End Using 'End Select Using
- myConn.Close()
- End Using
- End Try
- End If
- Catch ex As Exception
- MsgBox("Impossibile ottenere i dati dell'operatore. Errore: " & ex.Message)
- Err.Clear()
- End Try
- End Sub
- Private Sub RegistraLog(ByVal Operazione As String, ByVal Chiave As String)
- 'Inserisce il Log all'interno della tabella LOG_Operazioni
- Try
- Dim cn As New SqlConnection(connectionString)
- Dim s As String
- s = "Insert into LOG_OPERAZIONI(IdOperatore, Data, Ora, Operazione, Chiave)" & _
- " VALUES(@Operatore, @Data, @Ora, @Operazione, @Chiave)"
- Dim myCmd As New SqlCommand(s, cn)
- myCmd.Parameters.Add("@Operatore", SqlDbType.VarChar)
- myCmd.Parameters.Add("@Data", SqlDbType.DateTime)
- myCmd.Parameters.Add("@Ora", SqlDbType.NVarChar)
- myCmd.Parameters.Add("@Operazione", SqlDbType.VarChar)
- myCmd.Parameters.Add("@Chiave", SqlDbType.VarChar)
- myCmd.Parameters("@Operatore").Value = G_IDOPERATORE
- myCmd.Parameters("@Data").Value = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy").Substring(0, 10))
- myCmd.Parameters("@Ora").Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").Substring(Len("yyyy/MM/dd") + 1, 8)
- myCmd.Parameters("@Operazione").Value = Operazione
- myCmd.Parameters("@Chiave").Value = Chiave
- cn.Open()
- myCmd.ExecuteNonQuery()
- cn.Close()
- Catch ex As Exception
- MsgBox("Errore durante la scrittura dei log. Errore: " & ex.Message)
- End Try
- End Sub
- Private Sub CancellaDuplicatiIdTarga(ByVal tableName As String)
- 'Elimina i record duplicati confrontandeo ID e Targa.
- 'Elimina i record duplicati all'interno della tabella specificata tramite tableName
- Dim sqlStr As String = "DELETE FROM " & tableName & " WHERE ID NOT IN (SELECT MAX(ID) FROM " & tableName & " GROUP BY Targa HAVING MAX(ID) IS NOT NULL)"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlCommand(sqlStr, myConn)
- myCmd.ExecuteNonQuery()
- End Using
- myConn.Close()
- End Using
- End Sub
- Private Sub DettagliToSql(ByVal dt As DataTable)
- 'Inserisce nella tabella Dettagli le targhe presenti nel file Excel con i relativi dati presenti nel PDF.
- 'In caso di PDF mancante, corrotto o di errore nella lettura del PDF il metodo inserisce solamente la targa presente nel file Excel.
- 'Il parametro dt contiene la targa estratta dal file Excel del Cliente associata ai dati presenti all'interno dei PDF
- Dim rowIndex As Integer = 0
- Dim colIndex As Integer = 0
- Dim sqlStr As String
- Dim ID_DataTable As New System.Data.DataTable
- Dim ID_Testata As Integer
- sqlStr = "Select ID from TestateExcel where IdOperatore = '" & G_IDOPERATORE & "' AND NomeFile = '" & Path.GetFileName(fileExcel) & "' AND PathExcel = '" & fileExcel & "' AND PathPDF = '" & DirPdf & "'"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlDataAdapter(sqlStr, myConn)
- myCmd.Fill(ID_DataTable)
- End Using
- myConn.Close()
- End Using
- sqlStr = ""
- ID_Testata = Convert.ToInt16(ID_DataTable.Rows(0)(0))
- 'Inizio scrittura targhe senza pdf
- Dim errorDt As System.Data.DataTable = ErrorFinder()
- Try
- For Each dr In errorDt.Rows
- sqlStr = "INSERT INTO Dettagli (Targa, ID_Testate) VALUES ('"
- sqlStr = sqlStr & errorDt.Rows(rowIndex)(0) & "', " & ID_Testata & ")"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlCommand(sqlStr, myConn)
- myCmd.ExecuteNonQuery()
- End Using
- myConn.Close()
- End Using
- rowIndex += 1
- Next
- Catch ex As Exception
- Err.Clear()
- End Try
- 'Inizio inserimento Dettagli
- Try
- rowIndex = 0
- For Each dr In dt.Rows
- colIndex = 0
- sqlStr = "INSERT INTO Dettagli VALUES( "
- For Each dc In dt.Columns
- sqlStr = sqlStr & "'" & Convert.ToString(dt.Rows(rowIndex)(colIndex)).Replace("0.00.00", "").Replace(",", ".").Replace("'", "").Trim() & "', "
- colIndex += 1
- Next
- sqlStr = sqlStr & ID_Testata & ", "
- sqlStr = sqlStr.Substring(0, sqlStr.Length - 2) & ")"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlCommand(sqlStr, myConn)
- myCmd.ExecuteNonQuery()
- End Using
- myConn.Close()
- End Using
- rowIndex += 1
- Next
- Catch ex As Exception
- MsgBox(ex.Message)
- Finally
- 'CancellaDuplicatiIdTarga("Dettagli")
- RegistraLog("Inserimento targhe e dati relativi nella tabella dettagli.", "NULL")
- End Try
- End Sub
- Private Function ErrorFinder() As System.Data.DataTable
- 'Trova gli errori tramite la discrepanza tra i dati contenuti nella tabella TempTabXLS e nella tabella VISURE_PDF
- Dim dt As New System.Data.DataTable
- Try
- Dim sqlStr As String = "Select Targa FROM TempTabXLS WHERE Targa NOT IN (Select Targa From VISURE_PDF)"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myCmd As New SqlDataAdapter(sqlStr, myConn)
- myCmd.Fill(dt)
- End Using
- myConn.Close()
- End Using
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
- Return dt
- End Function
- Private Sub CreaCartellaPercorso()
- 'Crea il percorso di salvataggio dei dati e crea le cartelle opportune.
- 'Copia dei file PDF analizzati e del file Excel del Cliente nel percorso stabilito dal file .config
- Dim pathXls As String = My.Settings.PathXLS
- Dim pathPdf As String = My.Settings.PathPDF
- Dim pathFilePdf As String
- Try
- 'Creazione cartelle FILE_XLS / FILE_PDF
- If (Not System.IO.Directory.Exists(pathXls)) Then
- System.IO.Directory.CreateDirectory(pathXls)
- End If
- If (Not System.IO.Directory.Exists(pathPdf)) Then
- System.IO.Directory.CreateDirectory(pathPdf)
- End If
- 'Creazione sottocartelle singola elaborazione
- pathXls = pathXls & "\" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").ToLower.Replace("/", "").Replace(" ", "").Replace(".", "") & "_" & G_IDOPERATORE
- pathPdf = pathPdf & "\" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").ToLower.Replace("/", "").Replace(" ", "").Replace(".", "") & "_" & G_IDOPERATORE
- System.IO.Directory.CreateDirectory(pathXls)
- System.IO.Directory.CreateDirectory(pathPdf)
- pathXls = pathXls & "\" & Path.GetFileName(fileExcel)
- 'Copia file pdf nella sottocartella ed eliminazione file sorgente
- For Each x In My.Computer.FileSystem.GetFiles(DirPdf, FileIO.SearchOption.SearchTopLevelOnly)
- If Path.GetFileName(x).EndsWith(".pdf") Or Path.GetFileName(x).EndsWith(".PDF") Then
- pathFilePdf = pathPdf & "\" & Path.GetFileName(x)
- IO.File.Copy(x, pathFilePdf, False)
- End If
- Next
- IO.File.Copy(fileExcel, pathXls, False)
- DirPdf = pathPdf
- fileExcel = pathXls
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
- End Sub
- Private Sub InserisciTestata()
- 'Inserisce i dati all'interno della tabella Testata
- 'Dati inseriti: Nome del file Excel del Cliente, Id dell'operatore, data ed i path utilizzati per il salvataggio dei file
- Try
- Using myConn As New SqlConnection(connectionString)
- Dim sqlStr As String = "INSERT INTO TestateExcel VALUES(@NomeFile, @IdOperatore, @Data, @PathExcel, @PathPdf)"
- myConn.Open()
- Using myCmd As New SqlCommand(sqlStr, myConn)
- 'Creazione Parametri
- myCmd.Parameters.Add("@NomeFile", SqlDbType.NVarChar)
- myCmd.Parameters.Add("@IdOperatore", SqlDbType.Int)
- myCmd.Parameters.Add("@Data", SqlDbType.SmallDateTime)
- myCmd.Parameters.Add("@PathExcel", SqlDbType.NVarChar)
- myCmd.Parameters.Add("@PathPdf", SqlDbType.NVarChar)
- 'Inizializzazione Parametri
- myCmd.Parameters("@NomeFile").Value = Path.GetFileName(fileExcel)
- myCmd.Parameters("@IdOperatore").Value = Convert.ToInt16(G_IDOPERATORE)
- myCmd.Parameters("@Data").Value = DateTime.Now()
- myCmd.Parameters("@PathExcel").Value = fileExcel
- myCmd.Parameters("@PathPdf").Value = DirPdf
- 'Inserimento dati
- myCmd.ExecuteNonQuery()
- End Using
- End Using
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
- End Sub
- Private Sub Srch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Srch.Click
- 'Esegue la ricerca dei PDF legati alla targa richiesta in input tramite una query sulle tabelle Dettagli e Anagrafica.
- 'Stampa i risultati sulla maschera tramite una DataGridView
- Dim targa As String
- Dim dt As New System.Data.DataTable
- Try
- targa = TextBoxTarga.Text.Trim.ToUpper
- CancellaDuplicatiIdTarga("Dettagli")
- Dim sqlStr As String = "SELECT Targa, Telaio, Produttore, DataImmatricolazione as 'Data di Immatricolazione', DataCartaCircolazione as 'Data Rilascio C. di C.', KW, Classe, Cilindrata, Alimentazione, Tara, Posti, Assi, PrimaFormalita as 'Prima Formalità', DataPrimaFormalita as 'Data Prima Formalità', UltimaFormalita as 'Ultima Formalità', DataUltimaFormalita as 'Data Ultima Formalità', Atto, DataAtto as 'Data Atto', PrezzoVeicolo as 'Prezzo del Veicolo', Proprietario, Tipo as 'Sesso / Tipo società', DataNascita as 'Data di Nascita', ComuneNascita as 'Comune di Nascita', ComuneResidenza as 'Comune di Residenza', Indirizzo FROM Dettagli, Anagrafica WHERE Dettagli.Targa = @Targa AND Anagrafica.Targa_FK = @Targa"
- Using myConn As New SqlConnection(connectionString)
- myConn.Open()
- Using myDataAdapter As New SqlDataAdapter(sqlStr, myConn)
- myDataAdapter.SelectCommand.Parameters.Add("@Targa", SqlDbType.NVarChar)
- myDataAdapter.SelectCommand.Parameters("@Targa").Value = targa
- myDataAdapter.Fill(dt)
- End Using
- myConn.Close()
- End Using
- DataGridViewTarga.DataSource = dt
- saveExcelDataGrid = dt
- SaveExcelButton.Visible = True
- Catch ex As Exception
- MsgBox("Inserire una targa corretta prima di continuare.")
- End Try
- End Sub
- Private Sub CercaInsieme_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CercaInsieme.Click
- saveExcelDataGrid = DataTableToDataGrid(InsiemiToDataTable())
- SaveExcelButton.Visible = True
- End Sub
- Private Function DataTableToDataGrid(ByVal dt As System.Data.DataTable)
- Dim excelDataTable As New System.Data.DataTable
- CancellaDuplicatiIdTarga("Dettagli")
- Try
- Dim myConn As New SqlConnection(connectionString)
- Dim sqlStr As String = "SELECT Targa, Telaio, Produttore, DataImmatricolazione as 'Data di Immatricolazione', DataCartaCircolazione as 'Data Rilascio C. di C.', KW, Classe, Cilindrata, Alimentazione, Tara, Posti, Assi, PrimaFormalita as 'Prima Formalità', DataPrimaFormalita as 'Data Prima Formalità', UltimaFormalita as 'Ultima Formalità', DataUltimaFormalita as 'Data Ultima Formalità', Atto, DataAtto as 'Data Atto', PrezzoVeicolo as 'Prezzo del Veicolo', Proprietario, Tipo as 'Sesso / Tipo società', DataNascita as 'Data di Nascita', ComuneNascita as 'Comune di Nascita', ComuneResidenza as 'Comune di Residenza', Indirizzo FROM Dettagli, Anagrafica WHERE Dettagli.Targa = @Targa AND Anagrafica.Targa_FK = @Targa"
- Dim myDataAdapter As New SqlDataAdapter(sqlStr, myConn)
- myDataAdapter.SelectCommand.Parameters.Add("@Targa", SqlDbType.NVarChar)
- Dim j As Integer = 0
- myConn.Open()
- For Each dr In dt.Rows
- myDataAdapter.SelectCommand.Parameters("@Targa").Value = dt.Rows(j).Item(0)
- myDataAdapter.Fill(excelDataTable)
- j += 1
- Next
- myConn.Close()
- Catch ex As Exception
- MsgBox("Un errore è avvenuto durante la ricerca.")
- Err.Clear()
- End Try
- DataGridViewTarga.DataSource = excelDataTable
- Return excelDataTable
- End Function
- Private Function InsiemiToDataTable()
- Dim fileInsieme
- InsiemiExcel.InitialDirectory = "C:\"
- InsiemiExcel.Filter = "File Excel|*.xls; *.xlsx"
- If InsiemiExcel.ShowDialog = DialogResult.OK Then
- fileInsieme = InsiemiExcel.FileName
- InsiemeTextBox.Text = fileInsieme
- Else
- fileInsieme = Nothing
- End If
- Dim dt As New System.Data.DataTable
- Try
- Dim MyConnection As OleDbConnection
- Dim fileExcelType As String
- 'Individuo il tipo di file Excel scelto
- If IO.Path.GetExtension(fileInsieme.ToUpper) = ".XLS" Then
- fileExcelType = "Excel 8.0"
- MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileInsieme & "';Extended Properties=" & fileExcelType & ";")
- Else
- fileExcelType = "Excel 12.0"
- MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileInsieme & "';Extended Properties=" & fileExcelType & ";")
- End If
- ' Apre connessione con Excel
- MyConnection.Open()
- 'Popola data table
- Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
- Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
- MyCommand.TableMappings.Add("Table", " ")
- MyCommand.Fill(dt)
- MyConnection.Close()
- saveExcelDataGrid = dt
- Catch ex As Exception
- MsgBox("Impossibile aprire il file excel!")
- Err.Clear()
- End Try
- Return dt
- End Function
- Private Sub SaveExcelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveExcelButton.Click
- ExcelExport(saveExcelDataGrid, "", False)
- SaveExcelButton.Visible = False
- End Sub
- End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement