Generar reporte Excel desde un datagridview

Status
Not open for further replies.

Inocente

New member
Joined
Feb 16, 2024
Messages
1
Programming Experience
Beginner
Estimadas buenas tardes, con el permiso del administrador.

Soy aficionado a vb.net y estoy trabajando en un proyecto con vb.Net pero tengo problemas al momento de realizar informes de excel, este es el código que estoy empleando para realizar el informe el cual está construido en el módulo ReportesExcel. pero al llamar el reporte solo me imprime los encabezados y no los valores del datagridview, al principio si me funcionaba pero despues nada..

el proyecto no puedo adjuntar lo pero adjunto el link de descarga.


Imports Microsoft.Office.Interop.Excel
Imports System.Threading

Module ReportesExcel

Dim ProgressBarTimer As Timer
Sub ReporteExcelTipodeCambio()
' Crear e inicializar el formulario de progreso
Dim progressBarForm As New frm_BarraProgreso()
progressBarForm.Show()
progressBarForm.ProgressBar1.Maximum = frm_TipodeCambio.dtg_TipodeCambio.Rows.Count

Dim excelApp As New Application()
Dim ExcelLibro As Workbook = excelApp.Workbooks.Add
Dim ExcelHoja As Worksheet = CType(ExcelLibro.Worksheets(1), Worksheet)

' Definir la fila y columna inicial en la que se comenzará a escribir en Excel
Dim filaInicio As Integer = 9
Dim columnaInicio As Integer = 1

For i As Integer = 2 To frm_TipodeCambio.dtg_TipodeCambio.Columns.Count
Dim cell As Range = CType(ExcelHoja.Cells(filaInicio - 1, i + columnaInicio - 1), Range)

' Agregar texto en mayúsculas
cell.Value = UCase(frm_TipodeCambio.dtg_TipodeCambio.Columns(i - 1).HeaderText)

' Establecer el formato del texto y centrar
cell.Font.Bold = True
cell.HorizontalAlignment = XlHAlign.xlHAlignCenter

' Establecer bordes superior e inferior gruesos
cell.Borders(XlBordersIndex.xlEdgeTop).LineStyle = XlLineStyle.xlContinuous
cell.Borders(XlBordersIndex.xlEdgeTop).Weight = XlBorderWeight.xlThick
cell.Borders(XlBordersIndex.xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
cell.Borders(XlBordersIndex.xlEdgeBottom).Weight = XlBorderWeight.xlThick

' Establecer el relleno de color
cell.Interior.Color = RGB(191, 191, 191)
Next
ExcelHoja.Range("9:9").Select()
excelApp.ActiveWindow.FreezePanes = True

' Agregar texto en negrita y tamaño de letra 12 en la columna 2, fila 3
ExcelHoja.Cells(2, 2).Value = frm_Principal.txt_RazonSocial.Text
CType(ExcelHoja.Cells(2, 2), Range).Font.Bold = True
CType(ExcelHoja.Cells(2, 2), Range).Font.Size = 12

' Agregar texto en negrita y tamaño de letra 12 en la columna 2, fila 4
ExcelHoja.Cells(3, 2).Value = "D.N.I O R.U.C.: " & frm_Principal.txt_Ruc.Text
CType(ExcelHoja.Cells(3, 2), Range).Font.Bold = True
CType(ExcelHoja.Cells(3, 2), Range).Font.Size = 12

' Agregar texto en negrita y tamaño de letra 12 en la columna 2, fila 5
ExcelHoja.Cells(4, 2).Value = "Periodo: " & frm_Principal.txt_PerAnual.Text
CType(ExcelHoja.Cells(4, 2), Range).Font.Bold = True
CType(ExcelHoja.Cells(4, 2), Range).Font.Size = 12
Dim rowIndex As Integer = 0

ExcelHoja.Cells(6, 2).Value = "TIPO DE CAMBIO"
CType(ExcelHoja.Cells(6, 2), Range).Font.Bold = True
CType(ExcelHoja.Cells(6, 2), Range).Font.Size = 14
ExcelHoja.Range("B6:G6").Merge()
ExcelHoja.Cells(6, 2).HorizontalAlignment = XlHAlign.xlHAlignCenter

ProgressBarTimer = New Timer(AddressOf UpdateProgressBar, Nothing, 0, 5) ' Inicializar el temporizador

Do While rowIndex < frm_TipodeCambio.dtg_TipodeCambio.Rows.Count
' Formatear y grabar la primera columna (B) como fecha "dd/MM/yyyy" y centrada a la derecha
Dim fechaValue As Object = frm_TipodeCambio.dtg_TipodeCambio.Rows(rowIndex).Cells(0).Value
Dim fechaCell As Range = CType(ExcelHoja.Cells(rowIndex + filaInicio, columnaInicio), Range)

If fechaValue IsNot DBNull.Value AndAlso TypeOf fechaValue Is Date Then
fechaCell.Value = CDate(fechaValue).ToString("MM/dd/yyyy")
fechaCell.NumberFormat = "MM/dd/yyyy"
fechaCell.HorizontalAlignment = XlHAlign.xlHAlignRight
Else
' Tratar otros casos como cadena vacía o NULL
fechaCell.Value = If(fechaValue Is DBNull.Value OrElse fechaValue Is Nothing, "", fechaValue.ToString())
End If

' Grabar el resto de las columnas (de la columna 2 en adelante) con números decimales "0.0000"
For j As Integer = 1 To frm_TipodeCambio.dtg_TipodeCambio.Columns.Count - 1
Dim cell As Range = CType(ExcelHoja.Cells(rowIndex + filaInicio, j + columnaInicio), Range)
Dim cellValue As Object = frm_TipodeCambio.dtg_TipodeCambio.Rows(rowIndex).Cells(j).Value

If j >= 2 Then
If TypeOf cellValue Is DBNull OrElse cellValue Is Nothing Then
cell.Value = ""
ElseIf IsNumeric(cellValue) Then
cell.Value = CDbl(cellValue).ToString("0.0000")
cell.NumberFormat = "0.0000"
Else
cell.Value = cellValue.ToString()
End If
Else
' Para la primera columna (B), establecer el formato de fecha y alinear a la derecha
cell.NumberFormat = "MM/dd/yyyy"
cell.HorizontalAlignment = XlHAlign.xlHAlignRight

' Asignar el valor
cell.Value = cellValue
End If

Next

' Actualizar la barra de progreso
Dim porcentaje As Integer = (rowIndex + 1) * 100 \ frm_TipodeCambio.dtg_TipodeCambio.Rows.Count
Dim filas As Integer = (rowIndex + 1)
progressBarForm.Label1.Text = $"{porcentaje}%"
progressBarForm.Label2.Text = $"Procesando {filas} de {frm_TipodeCambio.dtg_TipodeCambio.Rows.Count} filas..."
progressBarForm.ProgressBar1.Value = rowIndex + 1

rowIndex += 1

' Pausar la ejecución para simular una operación más lenta
Thread.Sleep(5)
Loop

' Agregar borde inferior grueso en la última fila con valor, desde la columna B hasta la columna G
Dim ultimaFila As Integer = rowIndex + filaInicio - 1
CType(ExcelHoja.Range(ExcelHoja.Cells(ultimaFila, columnaInicio + 1), ExcelHoja.Cells(ultimaFila, columnaInicio + 6)), Range).Borders(XlBordersIndex.xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
CType(ExcelHoja.Range(ExcelHoja.Cells(ultimaFila, columnaInicio + 1), ExcelHoja.Cells(ultimaFila, columnaInicio + 6)), Range).Borders(XlBordersIndex.xlEdgeBottom).Weight = XlBorderWeight.xlThick
ExcelHoja.Cells(ultimaFila + 1, 2) = "Generado automáticamente por SOFT INOCENTE el " & frm_Impresion.txt_Fecha.Text
ExcelHoja.Cells(ultimaFila + 1, 2).Font.Bold = True

ExcelHoja.Range("A1").Select()

excelApp.WindowState = XlWindowState.xlMaximized
excelApp.Visible = True
' Detener el temporizador
ProgressBarTimer.Dispose()

' Cerrar el formulario de progreso después de completar el proceso
progressBarForm.Close()
End Sub

' Método para actualizar la barra de progreso en el hilo de la interfaz de usuario
Private Sub UpdateProgressBar(state As Object)
If ProgressBarTimer IsNot Nothing Then
ProgressBarTimer.Change(Timeout.Infinite, Timeout.Infinite) ' Detener el temporizador durante la actualización
End If
End Sub
 
Please translate to English and post again. Closing this thread.
 
Status
Not open for further replies.
Back
Top