Visual Basic.NET - ¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

 
Vista:
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por José Vicente (113 intervenciones) el 25/08/2021 13:42:34
Hola de nuevo, tengo un datagridview con el que añado valores a una Bd y genero una hoja excel con esos mismos valores. El problema es que cada vez que añado valores a la Bd me genera el Excel completo con lo que pierde el tiempo ya que lo suyo sería añadir los registros nuevos a la hoja y no crear una nueva.
No sé como hacer esto, sólo sé crear el Excel entero. ¿Puede alguien echarme un cable?. Gracias.
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
Imágen de perfil de Giancarlo
Val: 377
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por Giancarlo (488 intervenciones) el 25/08/2021 21:21:57
en el código que usas para esribir el archivo, agrega que lo abra y luego recorres todas las filas hasta que encuentres la última. te comento que no sería conveniente, porque cada vez que modificas la BD modificarías el excel, una especie de sincronización que te puede llevar más tiempo

te recomiendo usar closedxml para generar los archivos excel, lo hace rapidamente y en formato xlsx
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
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por José Vicente (113 intervenciones) el 26/08/2021 00:10:38
Hola, ¿Cómo puedo usar closedxml?, imagino que sería agregar el paquete de NuGet pero no he visto ningún ejemplo claro. ¿Puedes ayudarme a entenderlo? Gracias.
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
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por José Vicente (113 intervenciones) el 26/08/2021 05:15:20
Hola, ya había visto esa web, pero sigo sin tenerlo claro. lo que yo tengo es:

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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
Private Sub salir_btn_Click(sender As Object, e As EventArgs) Handles salir_btn.Click
 
        Dim hoy As Date = Now
 
        If hoy.DayOfWeek = DayOfWeek.Wednesday Then
 
            Try
 
                'AÑADIMOS EL LIBRO AL EXCEL Y LA HOJA AL LIBRO
 
                exLibro = exApp.Workbooks.Add
                exHoja = exApp.Sheets(1)
 
                'CONTAMOS COLUMNAS Y FILAS
 
                Dim NCol As Integer = DataGridView1.ColumnCount
                Dim NRow As Integer = DataGridView1.RowCount
 
                'RECORREMOS TODAS LAS FILAS Y POR CADA COLUMNA ESCRIBIMOS
 
                For i As Integer = 1 To NCol
 
                    exHoja.Cells.Item(1, i) = DataGridView1.Columns(i - 1).Name.ToString
 
                Next
 
                For Fila As Integer = 0 To NRow - 1
 
                    For Col As Integer = 0 To NCol - 1
 
                        exHoja.Cells.Item(Fila + 2, Col + 1) = DataGridView1.Rows(Fila).Cells(Col).Value
 
                    Next
 
                Next
 
                Dim M_Izq As Integer = 63
                Dim M_Der As Integer = 43
                Dim M_Sup As Integer = 35
                Dim M_Inf As Integer = 40
 
                'ORIENTACIÓN DE LA HOJA
 
                With exHoja.PageSetup
 
                    .Orientation = Excel.XlPageOrientation.xlPortrait
 
                    'CONFIGURACIÓN DE MÁRGENES
 
                    .LeftMargin = M_Izq
                    .RightMargin = M_Der
                    .TopMargin = M_Sup
                    .BottomMargin = M_Inf
 
                End With
 
                'TÍTULO EN NEGRITA, ALINEADO AL CENTRO DE LAS CELDAS Y COLOR
 
                Dim anio As Int16 = Now.Year
                Dim objRango As Excel.Range = exHoja.Range(exHoja.Cells(1, 1), exHoja.Cells(exHoja.UsedRange.Rows.Count, exHoja.UsedRange.Columns.Count))
                Dim contador As Integer = exHoja.Rows.Count
 
                exHoja.PageSetup.PrintTitleRows = exHoja.Rows(1).Address 'PONEMOS LA FILA DE ENCABEZADO EN TODAS LAS HOJAS IMPRESAS
                exHoja.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA4 'TAMAÑO DE PAPEL A4
                exHoja.Name = "Histórico tensión " & anio
                exHoja.Rows.Item(1).Font.Bold = 1 'NEGRITA
                exHoja.Rows.Item(1).Font.ColorIndex = 49 'COLOR DEL ENCABEZADO
                exHoja.Rows.Item(1).HorizontalAlignment = 3 'ALINEADO DEL ENCABEZADO
 
                objRango.HorizontalAlignment = 3 'ALINEADO DE LAS COLUMNAS
 
                exHoja.Range("A1").Value = "   FECHA   "
                exHoja.Range("B1").Value = "  SISTÓLICA  "
                exHoja.Range("C1").Value = "  DIASTÓLICA  "
                exHoja.Range("D1").Value = "  PULSACIONES  "
                exHoja.Range("E1").Value = "  SATURACIÓN  "
                exHoja.Range("A1:E1").Cells.Interior.Color = Color.Cyan
 
                objRango.Borders.LineStyle = 1 'BORDES DE LA HOJA
 
                exHoja.Rows.Font.Size = 12 ' TAMAÑO DE LA FUENTE
                exHoja.Rows.Font.Name = "Adobe Garamond Pro Bold" 'TIPO DE FUENTE
 
                exHoja.Columns.AutoFit() 'AJUSTE DE LAS COLUMNAS
 
                exHoja.Range("A2:A367").Font.ColorIndex = 5 'COLOR DE LA FUENTE DE LA COLUMNA DE FECHAS
                exHoja.Range("A2:A367").NumberFormat = "dd/mm/yyyy"
 
 
                'DAMOS FORMATO CONDICIONAL DE LAS CELDAS
                'FORMATO A COLUMNA DE FECHA
 
                For Fila As Integer = 2 To NRow + 1
 
                    For Col As Integer = 2 To NCol
 
                        Dim FC As String = Chr(64 + Col) & Fila
 
                        exHoja.Range(FC).Select()
                        exHoja.Range(FC).Font.ColorIndex = 1
                        exHoja.Range(FC).Font.Bold = True
 
                    Next
 
                Next
 
                'FORMATO A COLUMNA SISTÓLICA
 
                For Fila As Integer = 2 To NRow + 1
 
                    For Col As Integer = 2 To NCol - 3
 
                        Dim FC As String = Chr(64 + Col) & Fila
 
                        exHoja.Range(FC).Select()
 
                        If exHoja.Range(FC).Value >= 15 Or exHoja.Range(FC).Value <= 11 Then
 
                            exHoja.Range(FC).Font.ColorIndex = 3
                            exHoja.Range(FC).Font.Bold = True
 
                        End If
 
                    Next
 
                Next
 
                'FORMATO A COLUMNA DIASTÓLICA
 
                For Fila As Integer = 2 To NRow + 1
 
                    For Col As Integer = 3 To NCol - 2
 
                        Dim FC As String = Chr(64 + Col) & Fila
 
                        exHoja.Range(FC).Select()
 
                        If exHoja.Range(FC).Value <= 5 Or exHoja.Range(FC).Value >= 8 Then
 
                            exHoja.Range(FC).Font.ColorIndex = 3
                            exHoja.Range(FC).Font.Bold = True
 
                        End If
 
                    Next
 
                Next
 
                'FORMATO A COLUMNA PULSACIONES
 
                For Fila As Integer = 2 To NRow + 1
 
                    For Col As Integer = 4 To NCol - 1
 
                        Dim FC As String = Chr(64 + Col) & Fila
 
                        exHoja.Range(FC).Select()
 
                        If exHoja.Range(FC).Value <= 59 Or exHoja.Range(FC).Value >= 80 Then
 
                            exHoja.Range(FC).Font.ColorIndex = 3
                            exHoja.Range(FC).Font.Bold = True
 
                        End If
 
                    Next
 
                Next
 
                'FORMATO A COLUMNA SATURACIÓN
 
                For Fila As Integer = 2 To NRow + 1
 
                    For Col As Integer = 5 To NCol
 
                        Dim FC As String = Chr(64 + Col) & Fila
 
                        exHoja.Range(FC).Select()
 
                        If exHoja.Range(FC).Value <= 90 Then
 
                            exHoja.Range(FC).Font.ColorIndex = 3
                            exHoja.Range(FC).Font.Bold = True
 
                        End If
 
                    Next
 
                Next
 
                exHoja.Range("E1").End(Excel.XlDirection.xlDown).Select()
 
                'ESCRIBIMOS LAS MEDIAS DE CADA COLUMNA
 
                Dim ultimafila As Long
 
                ultimafila = exHoja.Range("A370").End(Excel.XlDirection.xlUp).Row
                ultimafila += 2
 
                exHoja.Cells(ultimafila, 1).Select()
                exHoja.Cells(ultimafila, 1).Value = "MEDIAS: "
                exHoja.Cells(ultimafila, 1).Font.ColorIndex = 32
                exHoja.Cells(ultimafila, 1).Interior.Color = Color.Chartreuse
                exHoja.Cells(ultimafila, 1).HorizontalAlignment = 3
                exHoja.Cells(ultimafila, 2).FormulaLocal = "=REDONDEAR(PROMEDIO(B2:B" & ultimafila - 2 & ");2)"
                exHoja.Cells(ultimafila, 2).HorizontalAlignment = 3
                exHoja.Cells(ultimafila, 3).FormulaLocal = "=REDONDEAR(PROMEDIO(C2:C" & ultimafila - 2 & ");2)"
                exHoja.Cells(ultimafila, 3).HorizontalAlignment = 3
                exHoja.Cells(ultimafila, 4).FormulaLocal = "=REDONDEAR(PROMEDIO(D2:D" & ultimafila - 2 & ");0)"
                exHoja.Cells(ultimafila, 4).HorizontalAlignment = 3
                exHoja.Cells(ultimafila, 5).FormulaLocal = "=REDONDEAR(PROMEDIO(E2:E" & ultimafila - 2 & ");0)"
                exHoja.Cells(ultimafila, 5).HorizontalAlignment = 3
 
                exHoja.Range("E1").End(Excel.XlDirection.xlDown).Select()
 
                'COMPROBAMOS SI EXISTE EL FICHERO Y LO SOBRESCRIBIMOS SI ES ASÍ
                'MOSTRAMOS EL MESSAGE BOX
 
                Dim archivo_anio As String = "D:\Documentos\Escaneados\Informe_medico_infarto_2019\Tensión\Historico tension " & anio & ".xlsx"
                Dim Message As String = "¿QUIERES GUARDAR LA HOJA EXCEL DEL AÑO?"
                Dim Caption As String = "OPCIÓN DE GUARDAR"
                Dim Buttons As MessageBoxButtons = MessageBoxButtons.YesNoCancel
 
                Dim Result As DialogResult
 
                Result = MessageBox.Show(Message, Caption, Buttons)
 
                ultimacelda = exHoja.Range("A1").End(Excel.XlDirection.xlDown).Value
 
                exApp.ActiveWindow.WindowState = Excel.XlWindowState.xlMaximized
 
                'RESULTADO DE LA OPCIÓN AFIRMATIVA
 
                If Result = System.Windows.Forms.DialogResult.No Then
 
                    If System.IO.File.Exists(archivo) = True And ultimacelda <> Now Then
 
                        'SI EL ARCHIVO EXISTE LO BORRAMOS Y GUARDAMOS EL NUEVO
 
                        System.IO.File.Delete(archivo)
                        exLibro.SaveAs(archivo)
 
                    ElseIf ultimacelda = Format(Now, "Short Date") Then
 
                        Dim P As System.Diagnostics.Process
 
                        Try
 
                            For Each P In System.Diagnostics.Process.GetProcesses
 
                                If P.ProcessName.ToUpper Like "*EXCEL*" Then
 
                                    P.Kill()
 
                                End If
 
                            Next
 
                        Catch
 
                        End Try
 
                        GC.WaitForPendingFinalizers()
                        GC.Collect()
 
                    Else
 
                        'SI NO EXISTE LO GUARDAMOS
 
                        exLibro.SaveAs(archivo)
 
                    End If
 
                    Dim Message1 As String = "FICHERO GUARDADO CON ÉXITO."
                    Dim Caption1 As String = "GUARDADO"
                    Dim Buttons1 As MessageBoxButtons = MessageBoxButtons.OK
 
                    Dim Result1 As DialogResult
 
                    Result1 = MessageBox.Show(Message1, Caption1, Buttons1)
 
                    'GUARDAMOS EL ARCHIVO TAMBIEN COMO PDF
 
                    Dim nombre As String = exHoja.Name
                    Dim ruta As String = "D:\Documentos\Escaneados\Informe_medico_infarto_2019\Tensión\"
 
                    exLibro.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, ruta & nombre & ".pdf", Excel.XlFixedFormatQuality.xlQualityStandard, True, True, 1, 30, False)
 
                ElseIf Result = System.Windows.Forms.DialogResult.Yes Then
 
                    If System.IO.File.Exists(archivo_anio) = True Then
 
                        'SI EL ARCHIVO EXISTE LO BORRAMOS Y GUARDAMOS EL NUEVO
 
                        System.IO.File.Delete(archivo_anio)
                        exLibro.SaveAs(archivo_anio)
 
                    Else
 
                        'SI NO EXISTE LO GUARDAMOS
 
                        exLibro.SaveAs(archivo_anio)
 
                    End If
 
                    Dim Message1 As String = "FICHERO GUARDADO CON ÉXITO."
                    Dim Caption1 As String = "GUARDADO"
                    Dim Buttons1 As MessageBoxButtons = MessageBoxButtons.OK
 
                    Dim Result1 As DialogResult
 
                    Result1 = MessageBox.Show(Message1, Caption1, Buttons1)
 
                End If
 
                'APLICACIÓN VISIBLE
 
                exApp.Application.Visible = True
 
                exHoja = Nothing
                exLibro = Nothing
                exApp = Nothing
 
            Catch ex As Exception
 
                MessageBox.Show(ex.Message, "ERROR AL EXPORTAR A EXCEL", MessageBoxButtons.OK, MessageBoxIcon.Error)
 
            End Try
 
            ' LIMPIAMOS TODOS LOS PROCESOS DE EXCEL ABIERTOS DE LA MEMORIA
 
            Try
 
                For Each P In System.Diagnostics.Process.GetProcesses
 
                    If P.ProcessName.ToUpper Like "*EXCEL*" Then
 
                        P.Kill()
 
                    End If
 
                Next
 
            Catch
 
            End Try
 
            GC.WaitForPendingFinalizers()
            GC.Collect()
 
        End If
 
        Me.Close()
        Form3.Close()
 
    End Sub
Ahí en el borrado del antiguo y guardado del nuevo es donde tengo que poner el código de editar el Excel ya existente.
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
Imágen de perfil de Giancarlo
Val: 377
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por Giancarlo (488 intervenciones) el 26/08/2021 05:35:23
mi codigo es este, sirve para enviar una lista de datatables a excel
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
Public Shared Sub generarExcel(ByVal lista() As DataTable, ByVal Titulo() As String)
            If lista(0) Is Nothing Then
                Return
            End If
            Dim workbook = New XLWorkbook
            Dim primeraFila As Integer = 1
            Dim primeraColumna As Integer = 1
 
            For iTabla As Integer = 0 To lista.Length - 1
                Dim tabla As DataTable = lista(iTabla)
                Dim worksheet = workbook.Worksheets.Add(Titulo(iTabla))
                Dim iColumna As Integer = 0
                Dim iFila As Integer = 0
 
                'ingresar titulos
                For Each columna As DataColumn In tabla.Columns
                    worksheet.Cell(primeraFila, primeraColumna + iColumna).DataType = XLCellValues.Text
                    worksheet.Cell(primeraFila, primeraColumna + iColumna).Value = columna.Caption
                    iColumna += 1
                Next
 
                'Ingresar los datos
                iFila = primeraFila
                For Each fila As DataRow In tabla.Rows
                    iFila += 1
                    iColumna = 0
                    For Each columna As DataColumn In tabla.Columns
                        worksheet.Cell(iFila, primeraColumna + iColumna).DataType = XLCellValues.Text
                        worksheet.Cell(iFila, primeraColumna + iColumna).Value = fila.Item(iColumna).ToString
                        iColumna += 1
                    Next
                Next
 
                'formato general
                With worksheet.Style
                    .Font.FontSize = 10
                    .Font.FontName = "Calibri"
                End With
 
                With worksheet.Style.Alignment
                    .Vertical = XLAlignmentVerticalValues.Center
                    .Horizontal = XLAlignmentHorizontalValues.Left
                    .WrapText = False
                End With
 
                'Formato de primera fila
                With worksheet.Range(primeraFila, _
                                     primeraColumna, _
                                     primeraFila, _
                                     primeraColumna + iColumna).Style
                    .Font.SetFontColor(XLColor.White)
                    .Font.SetBold(True)
                    .Fill.SetBackgroundColor(XLColor.Navy)
                End With
 
            Next
 
            'guardando el archivo
            Dim sfDialog As New SaveFileDialog
            sfDialog.Filter = "Hoja de calculos Excel|*xlsx"
            sfDialog.AddExtension = True
 
            'verificando para guardar
            If sfDialog.ShowDialog().Equals(DialogResult.OK) Then
                Dim destino As String = sfDialog.FileName
                If destino.PadRight(5) <> ".xlsx" Then
                    destino &= ".xlsx"
                End If
                workbook.SaveAs(destino)
                MsgBox("Archivo guardado", MsgBoxStyle.OkOnly, "Exportar archivo")
            End If
        End Sub
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
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por José Vicente (113 intervenciones) el 26/08/2021 11:48:40
hola, veo tu código pero no añades registros nuevos a la hoja, creas la hoja entera y lo que yo intento es añadir registros a la hoja.
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
Imágen de perfil de Giancarlo
Val: 377
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por Giancarlo (488 intervenciones) el 26/08/2021 15:54:36
debes recorrer las filas y luego agregas con este codigo:
1
2
3
4
5
6
7
8
9
10
11
 'Ingresar los datos
                iFila = primeraFila
                For Each fila As DataRow In tabla.Rows
                    iFila += 1
                    iColumna = 0
                    For Each columna As DataColumn In tabla.Columns
                        worksheet.Cell(iFila, primeraColumna + iColumna).DataType = XLCellValues.Text
                        worksheet.Cell(iFila, primeraColumna + iColumna).Value = fila.Item(iColumna).ToString
                        iColumna += 1
                    Next
                Next
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
sin imagen de perfil
Val: 229
Ha disminuido 1 puesto en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

¿Cómo puedo añadir registros a hoja excel sin tener que reescribirla toda?

Publicado por José Vicente (113 intervenciones) el 26/08/2021 16:13:51
Hola, voy a intentar acoplarlo en mi código y te cuento. Gracias.
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