Fallo al guardar DataSet en Excel
Publicado por José Vicente (113 intervenciones) el 23/09/2021 13:26:04
Hola, con el código:
Intento añadir el DataSet a la hoja Excel que ya tengo generada, y lo que consigo es que borre la última fila de la hoja y no añada ningún registro. ¿Como lo puedo arreglar? ¿Qué tengo mal?. Gracias.
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
Private Sub actualiza_btn_Click(sender As Object, e As EventArgs) Handles actualiza_btn.Click
Dim anio As String = CStr(Now.Year)
exApp = New Excel.Application
exLibro = exApp.Workbooks.Open("C:\Users\joviz\Downloads\Historico_tension.xlsx")
exHoja = DirectCast(exLibro.Sheets("Histórico tensión " & anio), Excel.Worksheet)
exHoja.Select()
Dim ultimaFila As Int16 = exHoja.Range("A1").End(Excel.XlDirection.xlDown).Row
Dim menorFecha As String = Format(exHoja.Range("$A$" & ultimaFila).Value, "dd/MM/yyy")
Dim rowIndex As Int16 = 0
'AVERIGUAMOS LA FILA DEL DGV DONDE ESTÁ LA ÚLTIMA FECHA GUARDADA EN LA HOJA EXCEL
For Each row As DataGridViewRow In DataGridView1.Rows
'SI LA FECHA DE LA COLUMNA COINCIDE CON LA FECHA BUSCADA
If CStr(row.Cells(0).Value) = menorFecha Then
'GUARDAMOS EL ÍNDICE DE LA FILA Y SALIMOS DEL FOR
rowIndex = row.Index
Exit For
End If
Next
Dim valorBuscado As Int16 = rowIndex + 1
Try
If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
Exit Sub
End If
'CREAMOS DATASET PARA EXPORTAR
Dim dset As New DataSet
'AGREGAMOS LA TABLA AL DATASET
dset.Tables.Add()
'AGREGAMOS COLUMNAS A LA TABLA
For i As Integer = 0 To DataGridView1.ColumnCount - 1
dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
Next
'AGREGAMOS FILAS A LA TABLA
Dim dr1 As DataRow
For i As Integer = valorBuscado To DataGridView1.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To DataGridView1.Columns.Count - 1
dr1(j) = DataGridView1.Rows(i).Cells(j).Value
Next
dset.Tables(0).Rows.Add(dr1)
Next
Dim dt As System.Data.DataTable = dset.Tables(0)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim contadorColumna As Int16 = 0
Dim contadorFila As Int16 = 0
For Each dc In dt.Columns
contadorColumna += 1
exApp.Cells(1, contadorColumna) = dc.ColumnName
Next
For Each dr In dt.Rows
contadorFila += 1
contadorColumna = 0
For Each dc In dt.Columns
contadorColumna += 1
exApp.Cells(valorBuscado + 1, contadorColumna) = dr(dc.ColumnName)
Next
Next
'CONFIGURAMOS LA ORIENTACIÓN DE LA HOJA Y EL TAMAÑO
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
exHoja.Range("E1").End(Excel.XlDirection.xlDown).Select()
Dim nombreFichero As String = "C:\Users\joviz\Downloads\Historico_tension.xlsx"
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(nombreFichero)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
End Try
MessageBox.Show("EL DOCUMENTO FUE ACTUALIZADO CORRECTAMENTE.", "MENSAJE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
exLibro.Save()
exApp.Workbooks.Open(nombreFichero)
exApp.Visible = True
Catch ex As Exception
MessageBox.Show(ex.Message, "DATOS DE TENSIÓN ARTERIAL DEL AÑO " & anio, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
' LIMPIAMOS TODOS LOS PROCESOS DE EXCEL ABIERTOS DE LA MEMORIA
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()
conexion.Close()
End Sub
Valora esta pregunta


0