Advertisement
LittleBoy0311

Merge excel with pdf

Mar 30th, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 25.79 KB | None | 0 0
  1. Imports iTextSharp.text
  2. Imports iTextSharp.text.api
  3. Imports iTextSharp.text.pdf
  4. Imports iTextSharp.text.pdf.parser
  5. Imports System.Text
  6. Imports System.IO
  7. Imports System
  8. Imports System.Data
  9. Imports System.Data.OleDb
  10. Imports System.Text.RegularExpressions
  11. Imports System.Data.SqlClient
  12. Imports Microsoft.VisualBasic.CompilerServices
  13. Imports System.Configuration
  14.  
  15.  
  16.  
  17. Public Class Visure
  18.  
  19.     Public Shared tabella As New Data.DataTable
  20.     Public Shared CnSql As SqlConnection
  21.     Public Shared CnSOGEUS As SqlConnection
  22.     Public Shared PATH_SERVER_PDF As String
  23.     Public Shared PATH_SERVER_REPORT As String
  24.     Public Shared PATH_SERVER_SPEDIZIONI As String
  25.     Public Shared PATH_SERVER_SOGEUS As String
  26.  
  27.     Public Shared IP_PATH_SERVER_PDF As String
  28.     Public Shared PATH_SERVER_PDF_OUTPUT As String
  29.     Public Shared IP_PATH_SERVER_PDF_OUTPUT As String
  30.     Dim DirPdf As String = ""
  31.     Dim fileExcel As String = ""
  32.     Dim Tab As String = "VISUREDAPDF_"
  33.     Dim TempTab As String = "TempExcelTable"
  34.     Dim connectionString As String = "Server=****;Database=****;User ID=****;Password=****;Integrated Security=SSPI;"
  35.  
  36.     Private Sub Exec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Exec.Click
  37.         Try
  38.             'Controlli input
  39.             Dim result As DialogResult = Windows.Forms.DialogResult.Yes
  40.  
  41.             If fileExcel = "" Or DirPdf = "" Then
  42.                 MsgBox("Selezionare un file excel ed una cartella pdf prima di continuare.")
  43.                 Exit Sub
  44.             End If
  45.  
  46.             If Path.GetFileNameWithoutExtension(fileExcel).Contains(Tab) Then
  47.                 result = MessageBox.Show("Un file excel già elaborato è stato selezionato, sei sicuro di voler continuare?", "Attenzione!", MessageBoxButtons.YesNo)
  48.             End If
  49.  
  50.             If result = DialogResult.Yes Then
  51.                 ProgressBar1.Value = 0
  52.                 Dim sDb As String
  53.                 If chkPgt.Checked Then
  54.                     sDb = "PEUGEOT"
  55.                     Tab = Tab.Replace("_", "_PAI")
  56.  
  57.                 Else
  58.                     sDb = "CITROEN"
  59.                     Tab = Tab.Replace("_", "_CAI")
  60.                 End If
  61.                 CnSqlOpen(sDb, connectionString)
  62.                 TableCleaner(Tab)
  63.                 ProgressBar1.Visible = True
  64.                 LeggiRinoninaPdfByTarga(DirPdf, 1, "aa", 1, Tab)
  65.                 ExcelManagment(fileExcel)
  66.             Else
  67.                 Exit Sub
  68.             End If
  69.         Catch ex As Exception
  70.             MsgBox("Un errore è stato rilvevato in Exec_Click. Errore:" & vbLf & ex.Message)
  71.             Err.Clear()
  72.         End Try
  73.     End Sub
  74.  
  75.     Public Function LeggiRinoninaPdfByTarga(ByVal sFolderPdfs As String, ByVal idTipoArchiviazionePDF As Integer, ByVal sDesTipo As String, ByVal lTestata As Long, ByVal Tab As String) As Boolean
  76.         Dim dir As DirectoryInfo
  77.         Dim file As FileInfo
  78.         Dim s As String
  79.         Dim sFileInput As String
  80.         Dim sFileTxt As String
  81.         Dim TableToExcel As New Data.DataTable
  82.         Dim counter As Integer = 0
  83.         LeggiRinoninaPdfByTarga = True
  84.  
  85.         Try
  86.  
  87.             dir = New DirectoryInfo(sFolderPdfs)
  88.  
  89.             For Each file In dir.GetFiles("*.PDF", SearchOption.TopDirectoryOnly)
  90.  
  91.                 sFileInput = file.Directory.ToString + "\" + file.Name.ToString
  92.                 sFileTxt = file.Directory.ToString + "\" + file.Name.ToString.Replace("PDF", "txt")
  93.  
  94.                 s = ParsePdfText(sFileInput)
  95.  
  96.                 My.Computer.FileSystem.WriteAllText(sFileTxt, s, False)
  97.  
  98.                 LeggiTargaEDateDaPdf(sFileTxt, sFileInput, idTipoArchiviazionePDF, sDesTipo, lTestata, Tab)
  99.  
  100.                 counter += 1
  101.  
  102.                 If counter Mod 20 = 0 Then
  103.                     ProgressBar1.PerformStep()
  104.                 End If
  105.             Next file
  106.             Return LeggiRinoninaPdfByTarga
  107.  
  108.         Catch ex As Exception
  109.             LeggiRinoninaPdfByTarga = False
  110.             Return LeggiRinoninaPdfByTarga
  111.         End Try
  112.  
  113.     End Function
  114.  
  115.     Public Shared Function ParsePdfText(ByVal sourcePDF As String, _
  116.                                    Optional ByVal fromPageNum As Integer = 0, _
  117.                                    Optional ByVal toPageNum As Integer = 0) As String
  118.         Dim sb As New System.Text.StringBuilder
  119.         Try
  120.             Dim reader As New iTextSharp.text.pdf.PdfReader(sourcePDF)
  121.             Dim pageBytes() As Byte = Nothing
  122.             Dim token As iTextSharp.text.pdf.PRTokeniser = Nothing
  123.             Dim tknType As Integer = -1
  124.             Dim tknValue As String = String.Empty
  125.  
  126.             If fromPageNum = 0 Then
  127.                 fromPageNum = 1
  128.             End If
  129.             If toPageNum = 0 Then
  130.                 toPageNum = reader.NumberOfPages
  131.             End If
  132.  
  133.             If fromPageNum > toPageNum Then
  134.                 Throw New ApplicationException("Errore parametri")
  135.             End If
  136.  
  137.             For i As Integer = fromPageNum To toPageNum Step 1
  138.                 pageBytes = reader.GetPageContent(i)
  139.                 If Not IsNothing(pageBytes) Then
  140.  
  141.                     token = New iTextSharp.text.pdf.PRTokeniser(pageBytes)
  142.                     While token.NextToken()
  143.                         tknType = token.TokenType()
  144.                         tknValue = token.StringValue
  145.                         Select Case tknType
  146.  
  147.                             Case 1  ' iTextSharp.text.pdf.PRTokeniser.TK_NUMBER
  148.                                 Dim dValue As Double
  149.                                 Dim r As Double
  150.                                 If Double.TryParse(tknValue, dValue, Nothing, r) Then
  151.                                     If dValue < -8000 Then
  152.                                         sb.Append(r)
  153.                                     End If
  154.                                 End If
  155.  
  156.                             Case 2  ' iTextSharp.text.pdf.PRTokeniser.TK_STRING
  157.                                 sb.Append(token.StringValue)
  158.                             Case 3  ' iTextSharp.text.pdf.PRTokeniser.TK_NAME
  159.                                 '
  160.                             Case 4  ' iTextSharp.text.pdf.PRTokeniser.TK_COMMENT    
  161.                                 '
  162.                             Case 5  ' iTextSharp.text.pdf.PRTokeniser.TK_START_ARRAY
  163.                                 '
  164.                             Case 6  ' iTextSharp.text.pdf.PRTokeniser.TK_END_ARRAY
  165.                                 sb.Append(Environment.NewLine)
  166.                                 'sb.Append(" ")
  167.                             Case 7  ' iTextSharp.text.pdf.PRTokeniser.TK_START_DIC
  168.                                 '
  169.                             Case 8  ' iTextSharp.text.pdf.PRTokeniser.TK_END_DIC
  170.                                 '
  171.                             Case 9  ' iTextSharp.text.pdf.PRTokeniser.TK_REF
  172.                                 '
  173.  
  174.                             Case 10 ' iTextSharp.text.pdf.PRTokeniser.TK_OTHER
  175.                                 Select Case tknValue
  176.                                     Case "TJ"
  177.                                         sb.Append(" ")
  178.                                     Case "ET"      ', "TD", "Td" , "Tm" , "T*"
  179.                                         sb.Append(Environment.NewLine)
  180.                                 End Select
  181.  
  182.                         End Select
  183.  
  184.  
  185.                     End While
  186.                 End If
  187.             Next i
  188.             reader.Close()
  189.         Catch ex As Exception
  190.             MsgBox("Un errore è stato rilvevato in ParePdfText. Errore:" & vbLf & ex.Message)
  191.             Err.Clear()
  192.             Return String.Empty
  193.         End Try
  194.  
  195.         Return sb.ToString()
  196.  
  197.     End Function
  198.  
  199.     Public Shared Sub LeggiTargaEDateDaPdf(ByVal sfileTxtInput As String, ByVal sfilePdfInput As String, ByVal TipoArchiviazionePDF As Integer, ByVal DesTipo As String, ByVal lTestata As Long, ByVal Tab As String)
  200.         Try
  201.             Dim reader As StreamReader
  202.             Dim readerDate As StreamReader
  203.             Dim FileTxt As FileInfo
  204.             Dim FilePdf As FileInfo
  205.             Dim sRiga As String
  206.             Dim sTarga As String
  207.             Dim sId As String
  208.             Dim sTelaio As String
  209.             Dim cmd As SqlCommand
  210.  
  211.             Dim text As New StringBuilder()
  212.  
  213.  
  214.             FileTxt = New System.IO.FileInfo(sfileTxtInput)
  215.             sId = FileTxt.Name.Substring(0, FileTxt.Name.LastIndexOf(".").ToString)
  216.             FilePdf = New System.IO.FileInfo(sfilePdfInput)
  217.  
  218.             reader = My.Computer.FileSystem.OpenTextFileReader(sfileTxtInput)
  219.             readerDate = My.Computer.FileSystem.OpenTextFileReader(sfileTxtInput)
  220.  
  221.             text.Append(readerDate.ReadToEnd)
  222.             Dim DateTrovate As MatchCollection = Regex.Matches(text.ToString, "[0-9]*/[0-9]*/[0-9]{4}")
  223.  
  224.             text = Nothing
  225.  
  226.             Dim bTargaPosizione As Boolean = False
  227.  
  228.             sRiga = reader.ReadLine.TrimStart
  229.  
  230.             Dim sFormalita As String
  231.  
  232.             Dim sDataUltForm As String
  233.             Dim sDataUltFormInizio As Integer
  234.             Dim sDataUltFormFine As Integer
  235.  
  236.             Dim tableriga As Data.DataRow = tabella.Rows.Add()
  237.             Dim iultimaforminizio As Integer
  238.             Dim iultimaformfine As Integer
  239.  
  240.             Dim iprezzoinizio As Integer
  241.             Dim iprezzofine As Integer
  242.             Dim sPrezzo As String
  243.  
  244.             Dim iprinizio As Integer
  245.             Dim iprfine As Integer
  246.             Dim sPr As String
  247.  
  248.             Dim isessnizio As Integer
  249.             Dim isessfine As Integer
  250.             Dim sSesso As String
  251.  
  252.  
  253.  
  254.             sTarga = Mid(sRiga, 22, 7)
  255.             sTelaio = Mid(sRiga, 35, 17)
  256.  
  257.             sDataUltFormInizio = sRiga.IndexOf("Data Ultima Formalita'") + 22
  258.             sDataUltFormFine = sDataUltFormInizio + 10
  259.             sDataUltForm = sRiga.Substring(sDataUltFormInizio, sDataUltFormFine - sDataUltFormInizio)
  260.  
  261.             iultimaforminizio = sRiga.IndexOf("Ultima Formalita'") + 17
  262.             iultimaformfine = sRiga.IndexOf("Data Ultima Formalita'")
  263.             sFormalita = sRiga.Substring(iultimaforminizio, iultimaformfine - iultimaforminizio)
  264.  
  265.             iprezzoinizio = sRiga.IndexOf("Prezzo del Veicolo") + 18
  266.             iprezzofine = sRiga.IndexOf("* Euro") - 1
  267.             sPrezzo = sRiga.Substring(iprezzoinizio, iprezzofine - iprezzoinizio).Replace("*", "").Replace(".", "").Replace(",", ".").Replace(" ", "")
  268.  
  269.             iprinizio = sRiga.IndexOf("Proprietario") + 12
  270.             iprfine = sRiga.IndexOf("Sesso / Tipo Societa'")
  271.             sPr = sRiga.Substring(iprinizio, iprfine - iprinizio)
  272.  
  273.             isessnizio = iprfine + 21
  274.             isessfine = sRiga.IndexOf("Data di nascita")
  275.             sSesso = sRiga.Substring(isessnizio, isessfine - isessnizio)
  276.             Dim sinsert As String
  277.             sinsert = "INSERT INTO " & Tab & " " & _
  278.                      "VALUES(" & fsql(sTarga, "T") & "," & fsql(sTelaio, "T") & "," & _
  279.                      sPrezzo & "," & fsql(sPr, "T") & "," & fsql(sSesso, "T") & ",'" & fsql(sFormalita, "T").ToString.Replace("'", "") & "'," & _
  280.                     fsql(sDataUltForm, "D") & ")"
  281.  
  282.             cmd = New SqlCommand(sinsert, CnSql)
  283.             cmd.CommandTimeout = 0
  284.             cmd.CommandType = CommandType.Text
  285.  
  286.             cmd.ExecuteNonQuery()
  287.  
  288.             reader.Close()
  289.             readerDate.Close()
  290.  
  291.             'Elimina il file txt analizzato
  292.             FileTxt.Delete()
  293.         Catch ex As Exception
  294.             MsgBox("Un errore è stato rilvevato in LeggiTargaDataPdf. Errore:" & vbLf & ex.Message)
  295.             Err.Clear()
  296.         End Try
  297.  
  298.     End Sub
  299.  
  300.     Public Shared Function CnSqlOpen(ByVal db As String, ByVal connectionString As String) As Boolean
  301.         Try
  302.             Dim flag As Boolean
  303.             If (CnSql Is Nothing) Then
  304.                 CnSql = New SqlConnection(connectionString)
  305.                 CnSql.Open()
  306.                 Return True
  307.             End If
  308.             If (CnSql.State = ConnectionState.Open) Then
  309.                 Return True
  310.             End If
  311.             CnSql = New SqlConnection(connectionString)
  312.             CnSql.Open()
  313.             flag = True
  314.             Return flag
  315.         Catch ex As Exception
  316.             MsgBox("Un errore è stato rilevato in CnSqlOpen. Errore:" & vbLf & ex.Message)
  317.         End Try
  318.     End Function
  319.  
  320.     Public Shared Function fsql(ByVal argDato As Object, ByVal argTipo As String) As Object
  321.         Try
  322.             Select Case argTipo
  323.                 'Intero'
  324.                 Case "I"
  325.  
  326.                     If IsNull(argDato) Then
  327.  
  328.                         Return " null "
  329.                     Else
  330.                         If Len(argDato) = 0 Then
  331.                             Return " null "
  332.                         Else
  333.                             Return argDato
  334.                         End If
  335.                     End If
  336.                     'Data'
  337.                 Case "D"
  338.                     If IsNull(argDato) Then
  339.                         Return " null "
  340.                     Else
  341.                         If Len(argDato) = 0 Then
  342.                             Return " null "
  343.                         Else
  344.                             Return "'" & argDato & "'"
  345.                         End If
  346.                     End If
  347.                     'Testo'
  348.                 Case "T"
  349.                     If IsNull(argDato) Then
  350.                         Return " null "
  351.                     Else
  352.                         If Len(argDato) = 0 Then
  353.                             Return " null "
  354.                         Else
  355.                             If InStr(argDato, Chr(39)) = 0 Then
  356.                                 Return "'" & (argDato) & "'"
  357.                             Else
  358.                                 Return "'" & Replace(argDato, "'", "''") & "'"
  359.                             End If
  360.                         End If
  361.                     End If
  362.                     'float'
  363.                 Case "F"
  364.                     If IsNull(argDato) Then
  365.                         Return " null "
  366.                     Else
  367.                         If Len(argDato) = 0 Then
  368.                             Return " null "
  369.                         Else
  370.                             If argDato - Int(argDato) <> 0 Then
  371.                                 Return Replace(argDato, ",", ".")
  372.                             Else
  373.                                 Return argDato
  374.                             End If
  375.                         End If
  376.                     End If
  377.                 Case "B"
  378.                     If IsNull(argDato) Then
  379.                         Return " null "
  380.                     Else
  381.                         If argDato = "Vero" Then
  382.                             Return " 1 "
  383.                         Else
  384.                             Return " 0 "
  385.                         End If
  386.                     End If
  387.             End Select
  388.         Catch ex As Exception
  389.             MsgBox("Un errore è stato rilevato in fsql. Errore:" & vbLf & ex.Message)
  390.             Err.Clear()
  391.         End Try
  392.         Return "null"
  393.     End Function
  394.  
  395.     Public Shared Function IsNull(ByVal arg As Object) As Boolean
  396.         Try
  397.             If Len(arg) = 0 Then
  398.                 Return True
  399.             Else
  400.                 Return False
  401.             End If
  402.  
  403.  
  404.         Catch ex As Exception
  405.             Return True
  406.         End Try
  407.     End Function
  408.  
  409.     Private Sub chkCitroen_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkCit.CheckedChanged
  410.         chkPgt.Checked = Not chkCit.Checked
  411.     End Sub
  412.  
  413.     Private Sub chkPgt_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkPgt.CheckedChanged
  414.         chkCit.Checked = Not chkPgt.Checked
  415.     End Sub
  416.  
  417.     Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  418.         chkPgt.Checked = True
  419.  
  420.     End Sub
  421.  
  422.     Private Sub UP_Excel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UP_Excel.Click
  423.         Try
  424.  
  425.             Excel_Check.ForeColor = Color.Green
  426.             Excel_Check.Text = ""
  427.             OpenFileExcel.InitialDirectory = "C:\"
  428.             OpenFileExcel.Filter = "File Excel|*.xls; *.xlsx"
  429.  
  430.             If OpenFileExcel.ShowDialog = DialogResult.OK Then
  431.                 fileExcel = OpenFileExcel.FileName
  432.                 Excel_Check.Text = "File selezionato correttamente."
  433.                 Excel_TextBox.Text = fileExcel
  434.                 If Path.GetFileNameWithoutExtension(fileExcel).ToUpper.Contains("CIT") Or Path.GetFileNameWithoutExtension(fileExcel).ToUpper.Contains("CAI") Then
  435.                     chkCit.Checked = True
  436.                 Else
  437.                     chkPgt.Checked = True
  438.                 End If
  439.             Else
  440.                 Excel_Check.ForeColor = Color.Red
  441.                 Excel_Check.Text = "Impossibile selezionare il file."
  442.                 Exit Sub
  443.             End If
  444.         Catch ex As Exception
  445.             MsgBox("Un errore è stato rilevato in Excel_Click. Errore:" & vbLf & ex.Message)
  446.             Err.Clear()
  447.         End Try
  448.     End Sub
  449.  
  450.     Private Sub UP_Pdf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UP_Pdf.Click
  451.         Try
  452.             Pdf_Check.ForeColor = Color.Green
  453.             Pdf_Check.Text = ""
  454.  
  455.             If OpenDirPdf.ShowDialog = DialogResult.OK Then
  456.                 DirPdf = OpenDirPdf.SelectedPath
  457.                 Pdf_Check.Text = "Cartella selezionata correttamente."
  458.                 PDF_TextBox.Text = DirPdf
  459.             Else
  460.                 Pdf_Check.ForeColor = Color.Red
  461.                 Pdf_Check.Text = "Impossibile selezionare la cartella."
  462.                 Exit Sub
  463.             End If
  464.         Catch ex As Exception
  465.             MsgBox("Un errore è stato rilevato in Pdf_Click. Errore:" & vbLf & ex.Message)
  466.             Err.Clear()
  467.         End Try
  468.     End Sub
  469.  
  470.     Private Sub ExcelManagment(ByVal filePath As String)
  471.         Try
  472.             Dim sFileName As String = filePath
  473.             Dim MyConnection As OleDbConnection
  474.             Dim DtTab As New System.Data.DataTable
  475.             Dim sTipoFile As String
  476.             ProgressBar1.Step = 10
  477.             'Individuo il tipo di file Excel scelto
  478.             If IO.Path.GetExtension(sFileName.ToUpper) = ".XLS" Then
  479.                 sTipoFile = "Excel 8.0"
  480.                 MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & sFileName & "';Extended Properties=" & sTipoFile & ";")
  481.  
  482.             Else
  483.                 sTipoFile = "Excel 12.0"
  484.                 MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sFileName & "';Extended Properties=" & sTipoFile & ";")
  485.             End If
  486.             ProgressBar1.PerformStep()
  487.             ' Apre connessione con Excel
  488.             MyConnection.Open()
  489.  
  490.             'Popola data table
  491.             Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
  492.             Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
  493.             MyCommand.TableMappings.Add("Table", "    ")
  494.             ProgressBar1.PerformStep()
  495.             MyCommand.Fill(DtTab)
  496.             MyConnection.Close()
  497.  
  498.             'insert and select datatable into db
  499.             TableCleaner(TempTab)
  500.             DataTableToSql(DtTab)
  501.  
  502.             'Popola tabella risultante
  503.             Dim RemoteDtTab As New System.Data.DataTable
  504.             Dim sql As String = "SELECT " & TempTab & ".Targa as 'Targa ACI', Modello, Dealer, CodiceDealer as 'Codice Dealer', Venduto as 'Venduta a', Valore as 'Valore vendite Eurotax', Telaio, PrezzodiVendita as 'Prezzo di Vendita', AttualeProprietario as 'Attuale Proprietatio', Tipo as 'Sesso/Tipo Società', UltimaFormalita as 'Ultima Formalità', DataUltimaFormalita as 'Data Ultima Formalità' FROM " & TempTab & ", " & Tab & " WHERE " & TempTab & ".Targa = " & Tab & ".Targa"
  505.             Using myConn As New SqlConnection(connectionString)
  506.                 myConn.Open()
  507.                 Using loader As New SqlDataAdapter(sql, myConn)
  508.                     loader.Fill(RemoteDtTab)
  509.                     ProgressBar1.Value = 100
  510.                     MsgBox("Elaborazione Completata.")
  511.                     ProgressBar1.Value = 0
  512.                 End Using
  513.             End Using
  514.  
  515.             'Export to excel
  516.             MsgBox("Inizio salvataggio file excel.")
  517.             Dim strFilePath As String= filePath.Replace(Path.GetFileName(filePath), "")
  518.             ExcelExport(RemoteDtTab, strFilePath)
  519.  
  520.         Catch ex As Exception
  521.             MsgBox("Un errore è stato rilevato in ExcelManagment. Errore:" & vbLf & ex.Message)
  522.         End Try
  523.     End Sub
  524.  
  525.     Private Sub ExcelExport(ByVal ExportDataTable As DataTable, ByVal filePath As String)
  526.         Try
  527.             ProgressBar1.Value = 0
  528.             ProgressBar1.Step = 1
  529.             ProgressBar1.PerformStep()
  530.             Dim excel As New Microsoft.Office.Interop.Excel.Application
  531.             Dim wBook As Microsoft.Office.Interop.Excel.Workbook
  532.             Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
  533.             wBook = excel.Workbooks.Add()
  534.             wSheet = wBook.ActiveSheet()
  535.  
  536.             Dim dt As System.Data.DataTable = ExportDataTable
  537.             Dim dc As System.Data.DataColumn
  538.             Dim dr As System.Data.DataRow
  539.             Dim colIndex As Integer = 0
  540.             Dim rowIndex As Integer = 0
  541.             Dim Counter As Integer = 0
  542.             'stop 5 - excel stuff declared
  543.  
  544.             For Each dc In dt.Columns
  545.                 colIndex = colIndex + 1
  546.                 excel.Cells(1, colIndex) = dc.ColumnName
  547.             Next
  548.             'stop 6 - Header written
  549.  
  550.             For Each dr In dt.Rows
  551.                 rowIndex = rowIndex + 1
  552.                 colIndex = 0
  553.                 Counter += 1
  554.                 If Counter Mod 10 = 0 Then
  555.                     ProgressBar1.PerformStep()
  556.                 End If
  557.                 For Each dc In dt.Columns
  558.                     colIndex = colIndex + 1
  559.                     excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
  560.                 Next
  561.             Next
  562.             ProgressBar1.Step = 10
  563.             ProgressBar1.PerformStep()
  564.             'stop 7 - rows written
  565.             Dim strFileName = filePath & Tab & ".xlsx"
  566.             If System.IO.File.Exists(strFileName) Then
  567.                 ProgressBar1.PerformStep()
  568.                 System.IO.File.Delete(strFileName)
  569.  
  570.             End If
  571.             ProgressBar1.PerformStep()
  572.             wBook.SaveAs(strFileName)
  573.             wBook.Close()
  574.             ProgressBar1.PerformStep()
  575.             excel.Quit()
  576.             ProgressBar1.Value = 100
  577.             MsgBox("File " & Path.GetFileName(strFileName) & " è stato salvato correttamente in " & strFileName)
  578.             Application.Restart()
  579.         Catch ex As Exception
  580.             MsgBox("Un errore è stato rilevato in ExcelEsport. Errore:" & vbLf & ex.Message)
  581.             Err.Clear()
  582.         End Try
  583.     End Sub
  584.  
  585.     Private Sub DataTableToSql(ByVal dt As DataTable)
  586.         Try
  587.             ProgressBar1.Step = 1
  588.             Dim myConn As New SqlConnection(connectionString)
  589.             Dim sqlCmd As String = "INSERT INTO " & TempTab & " VALUES(@Targa, @Modello, @Dealer, @Venduto, @CodiceDealer, @Valore)"
  590.             Dim myCmd As New SqlCommand(sqlCmd, myConn)
  591.             Dim counter As Integer = 0
  592.             myConn.Open()
  593.             myCmd.Parameters.Add("@Targa", SqlDbType.VarChar)
  594.             myCmd.Parameters.Add("@Modello", SqlDbType.VarChar)
  595.             myCmd.Parameters.Add("@Dealer", SqlDbType.VarChar)
  596.             myCmd.Parameters.Add("@CodiceDealer", SqlDbType.VarChar)
  597.             myCmd.Parameters.Add("@Venduto", SqlDbType.VarChar)
  598.             myCmd.Parameters.Add("@Valore", SqlDbType.Float)
  599.             For Each dr As DataRow In dt.Rows
  600.                 If chkCit.Checked Then
  601.                     myCmd.Parameters("@Targa").Value = dr(0).ToString
  602.  
  603.                     myCmd.Parameters("@Modello").Value = dr(1).ToString
  604.  
  605.                     myCmd.Parameters("@Dealer").Value = dr(2).ToString
  606.  
  607.                     myCmd.Parameters("@CodiceDealer").Value = dr(3).ToString
  608.  
  609.                     myCmd.Parameters("@Venduto").Value = dr(4).ToString
  610.  
  611.                     myCmd.Parameters("@Valore").Value = Convert.ToDouble(dr(5).ToString.Replace(",", "."))
  612.  
  613.                 Else
  614.  
  615.                     myCmd.Parameters("@Targa").Value = dr(0).ToString
  616.  
  617.                     myCmd.Parameters("@Modello").Value = dr(3).ToString
  618.  
  619.                     myCmd.Parameters("@Dealer").Value = dr(4).ToString
  620.  
  621.                     myCmd.Parameters("@Venduto").Value = dr(5).ToString
  622.  
  623.                     myCmd.Parameters("@CodiceDealer").Value = dr(6).ToString
  624.  
  625.  
  626.                     myCmd.Parameters("@Valore").Value = Convert.ToDouble(dr(7).ToString.Replace(",", "."))
  627.  
  628.                 End If
  629.                 myCmd.ExecuteNonQuery()
  630.                 counter += 1
  631.                 If counter Mod 20 = 0 Then
  632.                     ProgressBar1.PerformStep()
  633.                 End If
  634.  
  635.             Next
  636.             ProgressBar1.Value = 100
  637.             myConn.Close()
  638.         Catch ex As Exception
  639.             MsgBox("Un errore è stato rilevato in DataTableToSql. Errore:" & vbLf & ex.Message)
  640.             Exit Sub
  641.         End Try
  642.     End Sub
  643.  
  644.     Private Sub TableCleaner(ByVal tablename As String)
  645.         Try
  646.             Dim myConn As New SqlConnection(connectionString)
  647.             Dim myCmd As New SqlCommand("Delete from " & tablename, myConn)
  648.             myConn.Open()
  649.             myCmd.ExecuteNonQuery()
  650.             myConn.Close()
  651.         Catch ex As Exception
  652.             MsgBox("Un errore è stato rilevato in TableCleaner. Errore:" & vbLf & ex.Message)
  653.             Err.Clear()
  654.         End Try
  655.     End Sub
  656. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement