Você está na página 1de 10

Public Sub ExportarDatosExcel(ByVal DataGridView1 As DataGridView, ByVal titulo As

String)
Dim m_Excel As New Excel.Application
m_Excel.Cursor = Excel.XlMousePointer.xlWait
m_Excel.Visible = True
Dim objLibroExcel As Excel.Workbook = m_Excel.Workbooks.Add
Dim objHojaExcel As Excel.Worksheet = objLibroExcel.Worksheets(1)
With objHojaExcel
.Visible = Excel.XlSheetVisibility.xlSheetVisible
.Activate()
'Encabezado
.Range("A1:L1").Merge()
.Range("A1:L1").Value = "INSTITUTO ARGENCAF"
.Range("A1:L1").Font.Bold = True
.Range("A1:L1").Font.Size = 15
'Copete
.Range("A2:L2").Merge()
.Range("A2:L2").Value = titulo
.Range("A2:L2").Font.Bold = True
.Range("A2:L2").Font.Size = 12

Const primeraLetra As Char = "A"


Const primerNumero As Short = 3
Dim Letra As Char, UltimaLetra As Char
Dim Numero As Integer, UltimoNumero As Integer
Dim cod_letra As Byte = Asc(primeraLetra) - 1
Dim sepDec As String =
Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
Dim sepMil As String =
Application.CurrentCulture.NumberFormat.NumberGroupSeparator
'Establecer formatos de las columnas de la hija de c�lculo
Dim strColumna As String = ""
Dim LetraIzq As String = ""
Dim cod_LetraIzq As Byte = Asc(primeraLetra) - 1
Letra = primeraLetra
Numero = primerNumero
Dim objCelda As Excel.Range
For Each c As DataGridViewColumn In DataGridView1.Columns
If c.Visible Then
If Letra = "Z" Then
Letra = primeraLetra
cod_letra = Asc(primeraLetra)
cod_LetraIzq += 1
LetraIzq = Chr(cod_LetraIzq)
Else
cod_letra += 1
Letra = Chr(cod_letra)
End If
strColumna = LetraIzq + Letra + Numero.ToString
objCelda = .Range(strColumna, Type.Missing)
objCelda.Value = c.HeaderText
objCelda.EntireColumn.Font.Size = 8
'objCelda.EntireColumn.NumberFormat =
c.DefaultCellStyle.Format
If c.ValueType Is GetType(Decimal) OrElse c.ValueType Is
GetType(Double) Then
objCelda.EntireColumn.NumberFormat = "#" + sepMil +
"0" + sepDec + "00"
End If
End If
Next

Dim objRangoEncab As Excel.Range = .Range(primeraLetra +


Numero.ToString, LetraIzq + Letra + Numero.ToString)
objRangoEncab.BorderAround(1, Excel.XlBorderWeight.xlMedium)
UltimaLetra = Letra
Dim UltimaLetraIzq As String = LetraIzq

'CARGA DE DATOS
Dim i As Integer = Numero + 1

For Each reg As DataGridViewRow In DataGridView1.Rows


LetraIzq = ""
cod_LetraIzq = Asc(primeraLetra) - 1
Letra = primeraLetra
cod_letra = Asc(primeraLetra) - 1
For Each c As DataGridViewColumn In DataGridView1.Columns
If c.Visible Then
If Letra = "Z" Then
Letra = primeraLetra
cod_letra = Asc(primeraLetra)
cod_LetraIzq += 1
LetraIzq = Chr(cod_LetraIzq)
Else
cod_letra += 1
Letra = Chr(cod_letra)
End If
strColumna = LetraIzq + Letra
' ac� deber�a realizarse la carga
.Cells(i, strColumna) = IIf(IsDBNull(reg.ToString),
"", reg.Cells(c.Index).Value)
'.Cells(i, strColumna) = IIf(IsDBNull(reg.
(c.DataPropertyName)), c.DefaultCellStyle.NullValue, reg(c.DataPropertyName))
'.Range(strColumna + i, strColumna + i).In()

End If
Next
Dim objRangoReg As Excel.Range = .Range(primeraLetra +
i.ToString, strColumna + i.ToString)
objRangoReg.Rows.BorderAround()
objRangoReg.Select()
i += 1
Next
UltimoNumero = i

'Dibujar las l�neas de las columnas


LetraIzq = ""
cod_LetraIzq = Asc("A")
cod_letra = Asc(primeraLetra)
Letra = primeraLetra
For Each c As DataGridViewColumn In DataGridView1.Columns
If c.Visible Then
objCelda = .Range(LetraIzq + Letra +
primerNumero.ToString, LetraIzq + Letra + (UltimoNumero - 1).ToString)
objCelda.BorderAround()
If Letra = "Z" Then
Letra = primeraLetra
cod_letra = Asc(primeraLetra)
LetraIzq = Chr(cod_LetraIzq)
cod_LetraIzq += 1
Else
cod_letra += 1
Letra = Chr(cod_letra)
End If
End If
Next

'Dibujar el border exterior grueso


Dim objRango As Excel.Range = .Range(primeraLetra +
primerNumero.ToString, UltimaLetraIzq + UltimaLetra + (UltimoNumero - 1).ToString)

objRango.Select()
objRango.Columns.AutoFit()
objRango.Columns.BorderAround(1, Excel.XlBorderWeight.xlMedium)
End With

m_Excel.Cursor = Excel.XlMousePointer.xlDefault
End Sub
___________________________________________________________________________________
________

Public Function GridAExcel(ByVal DGV As DataGridView) As Boolean

'Creamos las variables

Dim exApp As New Microsoft.Office.Interop.Excel.Application


Dim exLibro As Microsoft.Office.Interop.Excel.Workbook
Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet

Try

exLibro = exApp.Workbooks.Add
exHoja = exLibro.Worksheets.Add()

' �Cuantas columnas y cuantas filas?


Dim NCol As Integer = DGV.ColumnCount
Dim NRow As Integer = DGV.RowCount
'recorremos todas las filas, y por cada fila todas las columnas
'y vamos escribiendo.
For i As Integer = 1 To NCol
exHoja.Cells.Item(1, i)=DGV.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)=
DGV.Rows(Fila).Cells(Col).Value()
Next

Next

'Titulo en negrita, Alineado


exHoja.Rows.Item(1).Font.Bold = 1
exHoja.Rows.Item(1).HorizontalAlignment = 3
exHoja.Columns.AutoFit()
'para visualizar el libro
exApp.Application.Visible = True
exHoja = Nothing
exLibro = Nothing
exApp = Nothing

Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error al exportar a Excel")

Return False
End Try
Return True
End Function

________________________________________________________________________________

Function GridAExcel(ByVal ElGrid As DataGridView) As Boolean

'Creamos las variables


Dim exApp As New Microsoft.Office.Interop.Excel.Application
Dim exLibro As Microsoft.Office.Interop.Excel.Workbook
Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet

Try
'A�adimos el Libro al programa, y la hoja al libro
exLibro = exApp.Workbooks.Add
exHoja = exLibro.Worksheets.Add()

' �Cuantas columnas y cuantas filas?


Dim NCol As Integer = ElGrid.ColumnCount
Dim NRow As Integer = ElGrid.RowCount

'Aqui recorremos todas las filas, y por cada fila todas las columnas y vamos
escribiendo.
For i As Integer = 1 To NCol
exHoja.Cells.Item(1, i) = ElGrid.Columns(i - 1).Name.ToString
'exHoja.Cells.Item(1, i).HorizontalAlignment = 3
Next

For Fila As Integer = 0 To NRow - 1


For Col As Integer = 0 To NCol - 1
exHoja.Cells.Item(Fila + 2, Col + 1) = ElGrid.Rows(Fila).Cells(Col).Value
Next
Next
'Titulo en negrita, Alineado al centro y que el tama�o de la columna se
ajuste al texto
exHoja.Rows.Item(1).Font.Bold = 1
exHoja.Rows.Item(1).HorizontalAlignment = 3
exHoja.Columns.AutoFit()
'Aplicaci�n visible
exApp.Application.Visible = True

exHoja = Nothing
exLibro = Nothing
exApp = Nothing

Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error al exportar a Excel")
'http://programaciontotal.blogspot.com
Return False
End Try

Return True

End Function

Para llamar a la funci�n es:

GridAExcel(nombreDeTuGrid)

_________________________________________________________________

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
DATAGRIDVIEW_TO_EXCEL((DataGridView1)) ' THIS PARAMETER IS YOUR DATAGRIDVIEW
End Sub

Private Sub DATAGRIDVIEW_TO_EXCEL(ByVal DGV As DataGridView)


Try
Dim DTB = New DataTable, RWS As Integer, CLS As Integer

For CLS = 0 To DGV.ColumnCount - 1 ' COLUMNS OF DTB


DTB.Columns.Add(DGV.Columns(CLS).Name.ToString)
Next

Dim DRW As DataRow

For RWS = 0 To DGV.Rows.Count - 1 ' FILL DTB WITH DATAGRIDVIEW


DRW = DTB.NewRow

For CLS = 0 To DGV.ColumnCount - 1


Try
DRW(DTB.Columns(CLS).ColumnName.ToString) =
DGV.Rows(RWS).Cells(CLS).Value.ToString
Catch ex As Exception

End Try
Next

DTB.Rows.Add(DRW)
Next

DTB.AcceptChanges()

Dim DST As New DataSet


DST.Tables.Add(DTB)
Dim FLE As String = "" ' PATH AND FILE NAME WHERE THE XML WIL BE CREATED
(EXEMPLE: C:\REPS\XML.xml)
DTB.WriteXml(FLE)
Dim EXL As String = "" ' PATH OF/ EXCEL.EXE IN YOUR MICROSOFT OFFICE
Shell(Chr(34) & EXL & Chr(34) & " " & Chr(34) & FLE & Chr(34),
vbNormalFocus) ' OPEN XML WITH EXCEL

Catch ex As Exception
MsgBox(ex.ToString)
End Try

End Sub

__________________________________________

Imports System.IO
Imports Excel = Microsoft.Office.Interop.Excel

sub export
Dim default_location As String = Application.StartupPath & "\Jadwal\" &
periode.Text & ".xls"
'Creating dataset to export
Dim dset As New DataSet
'add table to dataset
dset.Tables.Add()
'add column to that table
For i As Integer = 0 To dg2.ColumnCount - 1
dset.Tables(0).Columns.Add(dg2.Columns(i).HeaderText)
Next
'add rows to the table
Dim dr1 As DataRow
For i As Integer = 0 To dg2.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To dg2.Columns.Count - 1
dr1(j) = dg2.Rows(i).Cells(j).Value
Next
dset.Tables(0).Rows.Add(dr1)
Next

Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass


Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

excel.Visible = True
excel.UserControl = True

wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
wSheet = wBook.Sheets("sheet1")
excel.Range("A50:I50").EntireColumn.AutoFit()
With wBook
.Sheets("Sheet1").Select()
.Sheets(1).Name = "NameYourSheet"
End With

Dim dt As System.Data.DataTable = dset.Tables(0)


wSheet.Cells(1).value = periode.Text

For i = 0 To dg2.RowCount - 1
For j = 0 To dg2.ColumnCount - 1
wSheet.Cells(i + 1, j + 1).value = dg2.Rows(i).Cells(j).Value.tosring
Next j
Next i

wSheet.Columns.AutoFit()
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(default_location)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
End Try

If System.IO.File.Exists(default_location) Then
System.IO.File.Delete(default_location)
End If

wBook.SaveAs(default_location)
excel.Workbooks.Open(default_location)
excel.Visible = True
end sub

___________________________________________________________________

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim fichero As New SaveFileDialog()
fichero.Filter = "Excel (*.xls)|*.xls"
If fichero.ShowDialog() = DialogResult.OK Then
Dim aplicacion As Microsoft.Office.Interop.Excel.Application
Dim libros_trabajo As Microsoft.Office.Interop.Excel.Workbook
Dim hoja_trabajo As Microsoft.Office.Interop.Excel.Worksheet
aplicacion = New Microsoft.Office.Interop.Excel.Application()
libros_trabajo = aplicacion.Workbooks.Add()
hoja_trabajo = DirectCast(libros_trabajo.Worksheets.Item(1),
Microsoft.Office.Interop.Excel.Worksheet)
'Recorremos el DataGridView rellenando la hoja de trabajo
Dim columnsCount As Integer = ClientesDataGridView.Columns.Count
For i As Integer = 0 To ClientesDataGridView.Rows.Count - 2
For j As Integer = 0 To ClientesDataGridView.Columns.Count - 1
If i = 0 Then 'pintamos cabecera
hoja_trabajo.Cells(i + 1, j + 1) =
ClientesDataGridView.Columns(j).HeaderText
Else 'pintamos datos
hoja_trabajo.Cells(i + 1, j + 1) =
ClientesDataGridView.Rows(i).Cells(j).Value.ToString()
End If
Next
Next
libros_trabajo.SaveAs(fichero.FileName,
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal)
libros_trabajo.Close(True)
aplicacion.Quit()
End If
End Sub

__________________________________________________________________________

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load
'GENERAR Y RELLENAR EL DATAGRIDVIEW
Try
Dim n As Integer = 6 ' cualquier valor para sumar
Dim cantidad(n) As Integer 'matriz para almacenar hasta n valores
Dim valor As Double = 0.18 'valor de un articulo en com�n ....para
ejemplificar
Dim subtotal(n) As Double ' matriz que almacena los subtotales de cada
compra
Dim suma As Double 'total de la suma de la columna subtotal
For i As Integer = 0 To n - 1
cantidad(i) = i 'Val(InputBox("Ingresar cantidad N�" & i + 1))
'Entrada manual
Next
For i As Integer = 0 To n - 1
subtotal(i) = cantidad(i) * valor
suma = suma + subtotal(i)
Next
grid1.Rows.Add(n + 1) 'numero de filas del grid
For r As Integer = 0 To n - 1
grid1.Item(0, r).Value = r + 1
grid1.Item(1, r).Value = Format(cantidad(r), "0.00")
grid1.Item(2, r).Value = Format(valor, "0.00")
grid1.Item(3, r).Value = Format(subtotal(r), "0.00")
grid1.Item(2, n).Value = "TOTALES="
grid1.Item(3, n).Value = Format(suma, "0.00")
Next
Catch ex As KeyNotFoundException
MessageBox.Show("Error de concurrencia:" & vbCrLf & ex.Message)
End Try
End Sub

Private Sub BtnExcel_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles BtnExcel.Click
'Crer dataset para exportar
Dim dset As New DataSet
'add table to dataset
dset.Tables.Add()
'agregar columnas a la tabla
For i As Integer = 0 To grid1.ColumnCount - 1
dset.Tables(0).Columns.Add(grid1.Columns(i).HeaderText)
Next
'agregar filas a la tabla
Dim dr1 As DataRow
For i As Integer = 0 To grid1.RowCount - 1
dr1 = dset.Tables(0).NewRow
For j As Integer = 0 To grid1.Columns.Count - 1
dr1(j) = grid1.Rows(i).Cells(j).Value
Next
dset.Tables(0).Rows.Add(dr1)
Next
Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
wSheet.Name = "Ejemplo"
Dim dt As System.Data.DataTable = dset.Tables(0)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
excel.Visible = True
End Sub

_________________________________________________________

Você também pode gostar