Visual Basic.NET - Cerrar proceso de excel que se envia por email

 
Vista:
sin imagen de perfil

Cerrar proceso de excel que se envia por email

Publicado por Raul Alejandro (8 intervenciones) el 04/04/2016 22:36:19
Buen Dia,
El problema que tengo es que necesito recorrer una tabla de proveedores de SQL que contiene sus correos y dependiendo de su id de proveedores generarle dos reportes, guardarlos en una carpeta de red y después anexarlos como archivos adjuntos para enviarles un email automatico a cada uno, ya funciona la aplicación el detalle que tengo es que los procesos de Excel se me quedan abiertos y porque son muchos proveedores se quedan como 100 procesos de Excel abiertos, el código de la aplicación es el siguiente:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
*De aquí obtengo los id y correos de los proveedores*
 Dim DA3 As New SqlDataAdapter("SP", Conexion)
        DA3.SelectCommand.CommandType = CommandType.StoredProcedure
        Dim DT3 As New DataTable
        DA3.Fill(DT3)
*************************************************************
        If DT3.Rows.Count <> 0 Then
            '**Mata o elimina los archivos de la carpeta especificada**'
            Kill("direccion
            Dim FIla As DataRow


*Recorro todos los registros*
            For Each FIla In DT3.Rows
                '**El siguiente If valida si el no_proveedor es nulo o no**'
                If IsDBNull(FIla.Item("no_proveedor")) = True Then

                Else
                        Dim x As Decimal
                        Dim s As String
                        x = FIla.Item("no_proveedor")

                    If IsDBNull(FIla.Item("Email")) = False Then
                        s = FIla.Item("email")

                    End If

                        If IsDBNull(x) = True Then

                        Else
                            '**Consulta para OPReports No Confirmados**'
                        Dim DA As New SqlDataAdapter("SP", Conexion)
                            DA.SelectCommand.CommandType = CommandType.StoredProcedure
                            DA.SelectCommand.Parameters.AddWithValue("@x", x)
                            Dim DT As New DataTable
                            DT.Clear()
                            DA.Fill(DT)
                            DA.Dispose()

                             *Generar excel1*
                             Dim rowsTotal, colsTotal As Short
                            Dim I, j As Short
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
                            Dim xlApp As New Excel.Application
                            Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
                            Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Sheets(1), Excel.Worksheet)
                            xlApp.Visible = False
                            '**Procedimiento para validar que hay informacion en el OPReports No Confirmados**'
                            If DT.Rows.Count = 0 Then

                            Else
                                rowsTotal = DT.Rows.Count
                                colsTotal = DT.Columns.Count
                                With excelWorksheet
                                    .Name = "NON CONFIRMED ORDERS"
                                    .Cells.Select()
                                    .Cells.Delete()
                                    For I = 0 To rowsTotal - 1
                                        For j = 0 To colsTotal - 1
                                            .Cells(I + 3, j + 1).value = DT.Rows(I).Item(j)
                                        Next j
                                    Next I
                                    'Aqui van los datos del encabezado
                                    .Range("A1").FormulaR1C1 = "SUPPLIER"
                                    .Range("A2").FormulaR1C1 = "PROVEEDOR"
                                    .Range("B1").FormulaR1C1 = "PO"
                                    .Range("B2").FormulaR1C1 = "OC"
                                    .Range("C1").FormulaR1C1 = "CODE"
                                    .Range("C2").FormulaR1C1 = "CODIGO"
                                    .Range("D1").FormulaR1C1 = "DESCRIPTION"
                                    .Range("D2").FormulaR1C1 = "DESCRIPCION"
                                    .Range("E1").FormulaR1C1 = "SUP CODE"
                                    .Range("E2").FormulaR1C1 = "CODIGO PROVEEDOR"
                                    .Range("F1").FormulaR1C1 = "PO DATE"
                                    .Range("F2").FormulaR1C1 = "FECHA OC"
                                    .Range("G1").FormulaR1C1 = "REQ DATE"
                                    .Range("G2").FormulaR1C1 = "FECHA REQUERIDA"
                                    .Range("H1").FormulaR1C1 = "CONF DATE"
                                    .Range("H2").FormulaR1C1 = "FECHA CONFIRMADA"
                                    .Range("I1").FormulaR1C1 = "PROMISE DATE"
                                    .Range("I2").FormulaR1C1 = "FECHA PROMESA"
                                    .Range("J1").FormulaR1C1 = "AGING"
                                    .Range("J2").FormulaR1C1 = "DIAS TARDE"
                                    .Range("K1").FormulaR1C1 = "UOM"
                                    .Range("K2").FormulaR1C1 = "UNIDAD"
                                    .Range("L1").FormulaR1C1 = "REQ PCS"
                                    .Range("L2").FormulaR1C1 = "PCS REQ"
                                    .Range("M1").FormulaR1C1 = "DEL PCS"
                                    .Range("M2").FormulaR1C1 = "PCS SURTIDAS"
                                    .Range("N1").FormulaR1C1 = "BALANCE"
                                    .Range("N2").FormulaR1C1 = "SALDO"
                                    'Formato General
                                    .Range("1:1").Interior.Color = RGB(204, 192, 218)
                                    .Range("2:2").Interior.Color = RGB(204, 192, 218)
                                    .Range("F:I").NumberFormat = "[$-409]d-mmm-yy;@"
                                    .Columns("O:P").ClearContents()
                                    .Rows("1:1").Font.FontStyle = "Bold"
                                    .Rows("2:2").Font.FontStyle = "Bold"
                                    .Rows("2:2").Autofilter()
                                    .Cells.Columns.AutoFit()
                                    .Cells.Select()
                                    .Cells.EntireColumn.AutoFit()
                                    .Cells(1, 1).Select()
                                End With
                            excelBook.Application.ActiveWorkbook.SaveAs("direccion" & x & ".xlsx")
                            excelBook.Application.ActiveWorkbook.Application.Quit()
                            excelBook.Close()
                            xlApp.Quit()
                                xlApp = Nothing
                                excelBook = Nothing
                                excelWorksheet = Nothing
                                GC.Collect()
                            End If

                            '**Consulta para OPReports Confirmados**'
                        Dim DA2 As New SqlDataAdapter("SP", Conexion)
                            DA2.SelectCommand.CommandType = CommandType.StoredProcedure
                            DA2.SelectCommand.Parameters.AddWithValue("@x", x)
                            Dim DT2 As New DataTable
                            DT2.Clear()
                            DA2.Fill(DT2)
                            DA2.Dispose()
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
                            Dim xlApp2 As New Excel.Application
                            Dim excelBook2 As Excel.Workbook = xlApp2.Workbooks.Add
                            Dim excelWorksheet2 As Excel.Worksheet = CType(excelBook2.Sheets(1), Excel.Worksheet)
                            xlApp2.Visible = False
                            '**Procedimiento para validar que hay informacion en el OPReports Confirmados**'
                            If DT2.Rows.Count = 0 Then

                            Else
                                Dim rowsTotal2, colsTotal2 As Short
                                Dim I2, j2 As Short
                                With (excelWorksheet2)
                                    .Name = "OPEN PO REPORT"
                                    rowsTotal2 = DT2.Rows.Count
                                    colsTotal2 = DT2.Columns.Count
                                    For I2 = 0 To rowsTotal2 - 1
                                        For j2 = 0 To colsTotal2 - 1
                                            .Cells(I2 + 3, j2 + 1).value = DT2.Rows(I2).Item(j2)
                                        Next j2
                                    Next I2
                                    'Aqui van los datos del encabezado
                                    .Range("A1").FormulaR1C1 = "SUPPLIER"
                                    .Range("A2").FormulaR1C1 = "PROVEEDOR"
                                    .Range("B1").FormulaR1C1 = "PO"
                                    .Range("B2").FormulaR1C1 = "OC"
                                    .Range("C1").FormulaR1C1 = "CODE"
                                    .Range("C2").FormulaR1C1 = "CODIGO"
                                    .Range("D1").FormulaR1C1 = "DESCRIPTION"
                                    .Range("D2").FormulaR1C1 = "DESCRIPCION"
                                    .Range("E1").FormulaR1C1 = "SUP CODE"
                                    .Range("E2").FormulaR1C1 = "CODIGO PROVEEDOR"
                                    .Range("F1").FormulaR1C1 = "PO DATE"
                                    .Range("F2").FormulaR1C1 = "FECHA OC"
                                    .Range("G1").FormulaR1C1 = "REQ DATE"
                                    .Range("G2").FormulaR1C1 = "FECHA REQUERIDA"
                                    .Range("H1").FormulaR1C1 = "CONF DATE"
                                    .Range("H2").FormulaR1C1 = "FECHA CONFIRMADA"
                                    .Range("I1").FormulaR1C1 = "PROMISE DATE"
                                    .Range("I2").FormulaR1C1 = "FECHA PROMESA"
                                    .Range("J1").FormulaR1C1 = "AGING"
                                    .Range("J2").FormulaR1C1 = "DIAS TARDE"
                                    .Range("K1").FormulaR1C1 = "UOM"
                                    .Range("K2").FormulaR1C1 = "UNIDAD"
                                    .Range("L1").FormulaR1C1 = "REQ PCS"
                                    .Range("L2").FormulaR1C1 = "PCS REQ"
                                    .Range("M1").FormulaR1C1 = "DEL PCS"
                                    .Range("M2").FormulaR1C1 = "PCS SURTIDAS"
                                    .Range("N1").FormulaR1C1 = "BALANCE"
                                    .Range("N2").FormulaR1C1 = "SALDO"
                                    'Formato General
                                    .Range("1:1").Interior.Color = RGB(204, 192, 218)
                                    .Range("2:2").Interior.Color = RGB(204, 192, 218)
                                    .Range("F:I").NumberFormat = "[$-409]d-mmm-yy;@"
                                    .Columns("O:P").ClearContents()
                                    .Rows("1:1").Font.FontStyle = "Bold"
                                    .Rows("2:2").Font.FontStyle = "Bold"
                                    .Rows("2:2").Autofilter()
                                    .Cells.Columns.AutoFit()
                                    .Cells.Select()
                                    .Cells.EntireColumn.AutoFit()
                                    .Cells(1, 1).Select()
                                End With
                            excelBook2.Application.ActiveWorkbook.SaveAs("direccion& x & ".xlsx")
                            excelBook2.Application.ActiveWorkbook.Application.Quit()
                            xlApp2.Quit()
                            xlApp2 = Nothing
                                excelBook2 = Nothing
                                excelWorksheet2 = Nothing
                                GC.Collect()
                            End If
                        GC.Collect()
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil

Cerrar proceso de excel que se envia por email

Publicado por Raul Alejandro (8 intervenciones) el 04/04/2016 22:53:12
La segunda parte del código..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
  '**Aqui se comienza a enviar el correo**'
                            Try
                                Dim cadena As String
                                Dim SmtpServer As New SmtpClient()
                                Dim mail As New MailMessage()
                            Dim destinatarios As String = "correo"
                                SmtpServer.Port = 25
                                SmtpServer.Host = "servidor"
                                mail = New MailMessage()
                                mail.From = New MailAddress("correo")
                                mail.To.Add(destinatarios)
                                mail.Priority = MailPriority.High
                                mail.IsBodyHtml = True
                                mail.Subject = "Supplier Open Order Report"
                                'Aqui va el Cuerpo del correo
                                cadena =   cuerpo de correo
                                '**Aqui se valida si se crearon los archivos a anexar o no existen**'
                            Dim File1 As String = "direccion_" & x & ".xlsx"
                                If File.Exists((File1)) = True Then
                                Dim archivo As New System.Net.Mail.Attachment("direccion_" & x & ".xlsx")
                                    mail.Attachments.Add(archivo)
                                End If
                            Dim File2 As String = "direccion_" & x & ".xlsx"
                                If File.Exists((File2)) = True Then
                                Dim archivo2 As New System.Net.Mail.Attachment("direccion" & x & ".xlsx")
                                    mail.Attachments.Add(archivo2)
                                End If
                                '**Envio del Correo
                                SmtpServer.Send(mail)
                            Application.DoEvents()
                            mail.Attachments.Dispose()
                            mail.Dispose()
                            SmtpServer.Dispose()
                            If IsDBNull(FIla.Item("Email")) = False Then
                                Conexion.Open()
                                Dim CMD As New SqlCommand("Sp", Conexion)
                                CMD.CommandType = CommandType.StoredProcedure
                                CMD.Parameters.AddWithValue("@x", x)
                                CMD.Parameters.AddWithValue("@fecha", Date.Now)
                                CMD.Parameters.AddWithValue("@correo", s)
                                CMD.ExecuteNonQuery()
                                Conexion.Close()
                            End If
 
                            xlApp2 = Nothing
                            excelBook2 = Nothing
                            excelWorksheet2 = Nothing
                            xlApp = Nothing
                            excelBook = Nothing
                            excelWorksheet = Nothing
                        Catch
                            MsgBox(Err.Description)
                            ListBox1.Visible = True
                            LblError.Visible = True
                            ListBox1.Items.Add(x)
                            xlApp2 = Nothing
                            excelBook2 = Nothing
                            excelWorksheet2 = Nothing
                            xlApp = Nothing
                            excelBook = Nothing
                            excelWorksheet = Nothing
 
                            GC.Collect()
                            'Aqui va el error que presento 
                            'Err.Description
                        Finally
 
                            xlApp2 = Nothing
                            excelBook2 = Nothing
                            excelWorksheet2 = Nothing
                            xlApp = Nothing
                            excelBook = Nothing
                            excelWorksheet = Nothing
                            GC.Collect()
                        End Try
                     End If
                End If
            Next
        End If
    End Sub


Se que falta el excelbook.close, y el xlapp.quit , el problema es que si lo coloco marca un error porque dice que se ha desconectado de los clientes y marca un error, gracias y saludos.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar