Foros del Web » Programación para mayores de 30 ;) » .NET »

importar y exportar a Excel : Visual Basic 2005

Estas en el tema de importar y exportar a Excel : Visual Basic 2005 en el foro de .NET en Foros del Web. Hola amigos a ver quien me puede ayudar. Tengo un DataGridView1 , ahi cargo lo que tengo en excel con un path fijo (Ej: C:\test.xls) ...
  #1 (permalink)  
Antiguo 08/08/2011, 08:12
Avatar de moradazo  
Fecha de Ingreso: julio-2008
Ubicación: [email protected]
Mensajes: 355
Antigüedad: 15 años, 10 meses
Puntos: 2
importar y exportar a Excel : Visual Basic 2005

Hola amigos a ver quien me puede ayudar.

Tengo un DataGridView1, ahi cargo lo que tengo en excel con un path fijo (Ej: C:\test.xls)

Tengo un botón para agregar filas al datagridview, todo bien hasta ahí

El problema es en el momento de exportar, me aseguro de cerrar la lectura del excel y cuando le doy me da muchos errores distintos, por ejemplo:

El índice no es válido. (Excepción de HRESULT: 0x8002000B (DISP_E_BADINDEX))
El formato no es válido, etc.

Lo que quiero realmente es salvar los datos que se agregan nuevos al mismo archivo de excel.

La referencia agregué la 11, la válida para Office 2003.

dgg es el DataGridView

Código vb:
Ver original
  1. Imports Excel = Microsoft.Office.Interop.Excel
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Imports System.Windows.Forms
  5. Imports System.IO
  6. Imports System.Data.OleDb
  7. Public Class Form1
  8.     Inherits System.Windows.Forms.Form
  9.     Private MiConexion As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties = 'Excel 8.0'; Data Source=C:\prueba.xls;")
  10.     Private MiAdaptador As New OleDbDataAdapter("SELECT * FROM [Hoja1$]", MiConexion)
  11.     Private MiDataSet As New DataSet()
  12.     Private MiEnlazador As New BindingSource
  13.  
  14.     Private Sub Update_Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Update_Btn.Click
  15.         Dim commandbuilder As New OleDb.OleDbCommandBuilder(Me.MiAdaptador)
  16.         MiConexion.Open()
  17.         MiAdaptador.Fill(MiDataSet)
  18.         MiEnlazador.DataSource = MiDataSet.Tables(0)
  19.         Me.dgg.DataSource = MiEnlazador
  20.     End Sub
  21.     Private Sub agregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agregar_Btn.Click
  22.         Try
  23.             Dim nombre As DataRow
  24.             nombre = MiDataSet.Tables(0).NewRow()
  25.             nombre("Nombre") = TB_nombre.Text
  26.             nombre("Teléfono") = TB_telefono.Text
  27.             nombre("Motivo") = TB_motivo.Text
  28.             nombre("Otros") = TB_otros.Text
  29.             MiDataSet.Tables(0).Rows.Add(nombre)
  30.             Me.MiAdaptador.Update(CType(Me.MiEnlazador.DataSource, DataTable))
  31.         Catch
  32.         End Try
  33.     End Sub
  34.  
  35.     Private Sub Export_Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Export_Btn.Click
  36.         'Creamos las variables
  37.        Dim exLibro As Excel.Workbook
  38.         Dim exHoja As Excel.Worksheet
  39.         Dim exApp As New Excel.Application 'Se debe agregar la referencia en el proyecto para usar esta función
  40.        ' Variables para # de columnas y # de renglones
  41.        Dim iCol As Integer
  42.         Dim iRow As Integer
  43.         Try
  44.             'Añadimos el Libro al programa, y la hoja al libro
  45.            exLibro = exApp.Workbooks("C:\prueba.xls")
  46.             exHoja = exLibro.Worksheets("Hoja1")
  47.             iCol = dgg.Columns.Count 'MiDato2
  48.            iRow = dgg.Rows.Count 'MiDato1
  49.            If iCol = 0 Then
  50.                 MsgBox("No hay información por exportar a Excel", MsgBoxStyle.Information, "mi programa")
  51.             Else
  52.                 'Aqui recorremos todas las filas
  53.                For i As Integer = 1 To iCol
  54.                     If dgg.Columns(i - 1).Visible = True Then
  55.                         exHoja.Cells.Item(1, i) = dgg.Columns(i - 1).Name.ToString
  56.                         exHoja.Cells.Item(1, i).HorizontalAlignment = 3
  57.                     End If
  58.                 Next
  59.                 'Por cada fila pone todas las columnas y vamos escribiendo.
  60.                For Fila As Integer = 0 To iRow - 1
  61.                     For Col As Integer = 0 To iCol - 1
  62.                         If dgg.Columns(Col).Visible = True Then
  63.                             exHoja.Cells.Item(1, Col + 1) = dgg.Columns(Col).HeaderText 'Estas son las columnas del encabezado
  64.                            exHoja.Cells.Item(Fila + 2, Col + 1) = dgg.Rows(Fila).Cells(Col).Value
  65.                         End If
  66.                     Next
  67.                 Next
  68.                 exLibro.SaveAs("C:\prueba.xls")
  69.                 exApp.Application.Visible = True
  70.             End If
  71.             'Se eliminan las variables de objeto excel
  72.            exApp = Nothing
  73.             exHoja = Nothing
  74.             exLibro = Nothing
  75.         Catch ex As Exception
  76.             MsgBox(ex.Message, MsgBoxStyle.Information, "Error al exportar a Excel")
  77.             Return
  78.         End Try
  79.         Return
  80.     End Sub
  81. End Class
  #2 (permalink)  
Antiguo 08/08/2011, 17:39
Avatar de moradazo  
Fecha de Ingreso: julio-2008
Ubicación: [email protected]
Mensajes: 355
Antigüedad: 15 años, 10 meses
Puntos: 2
Respuesta: importar y exportar a Excel : Visual Basic 2005

Hola a todos, al menos pude ya lograr importar a mi datagrid y expotar a excel. El único detalle es que no puedo agregar filas o "rows" ya que el datagrid se encuentra enlazado por haber importado un archivo de excel, y no me deja ingresar nuevas filas de ningún modo:



Por ejemplo he intentado con un While pero no funciona:

DataGridView1.Rows(i).Cells(0).Value = Textbox1.Text

O con el agregar normal:

DataGridView1.Rows.Add()

Alguien me puede dar una mano en como agregar filas nuevas con el datagrid enlazado?

Gracias

Aqui el código de importar y exportar:

Código vb:
Ver original
  1. Imports System.Data.SqlClient
  2. Imports System.Data.OleDb
  3. Public Class Form1
  4.     Inherits System.Windows.Forms.Form
  5.     Private MiDataSet As New DataSet()
  6.     Private MiEnlazador As New BindingSource
  7.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  8.         Dim abrir As New OpenFileDialog
  9.         abrir.Filter = "Archivo de excel|*.xls"
  10.         If abrir.ShowDialog = Windows.Forms.DialogResult.OK Then
  11.             importexcel(abrir.FileName)
  12.         End If
  13.     End Sub
  14.     Private Sub importexcel(ByVal path As String)
  15.         Dim sconnectionstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _
  16.         & "Data Source=" + path + "" _
  17.         & ";" & "Extended Properties=Excel 8.0;"
  18.         Dim objconn As New OleDb.OleDbConnection(sconnectionstring)
  19.         objconn.Open()
  20.         Dim objcmdselect As New OleDb.OleDbCommand("SELECT * FROM [Hoja1$]", objconn)
  21.         Dim objadapter1 As New OleDb.OleDbDataAdapter()
  22.         objadapter1.SelectCommand = objcmdselect
  23.         Dim objdataset1 As New DataSet()
  24.         objadapter1.Fill(objdataset1, "XLData")
  25.         Me.DataGridView1.DataSource = objdataset1.Tables(0).DefaultView
  26.         objconn.Close()
  27.     End Sub
  28.  
  29.     Public Sub exportaraexcel(ByVal dgv As DataGridView, ByVal pth As String)
  30.         Dim xlapp As Object = createobject("Excel.Application")
  31.         Dim xlwb As Object = xlapp.workbooks.add
  32.         Dim xlws As Object = xlwb.Worksheets(1)
  33.  
  34.         For C As Integer = 0 To datagridview1.columns.count - 1
  35.             xlws.cells(1, c + 1).value = Datagridview1.columns(c).headertext
  36.         Next
  37.         For r As Integer = 0 To datagridview1.rowcount - 1
  38.             For c As Integer = 0 To datagridview1.columns.count - 1
  39.                 xlws.cells(r + 2, c + 1).Value = datagridview1.item(c, r).Value
  40.             Next
  41.         Next
  42.  
  43.         xlwb.saveas(pth)
  44.         xlws = Nothing
  45.         xlwb = Nothing
  46.         xlapp.quit()
  47.         xlapp = Nothing
  48.     End Sub
  49.  
  50.  
  51.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  52.         Dim save As New SaveFileDialog
  53.         save.Filter = "Archivo Excel | *.xls"
  54.  
  55.         If save.ShowDialog = Windows.Forms.DialogResult.OK Then
  56.             exportaraexcel(Me.DataGridView1, save.FileName)
  57.         End If
  58.     End Sub
  #3 (permalink)  
Antiguo 09/08/2011, 14:38
 
Fecha de Ingreso: julio-2011
Mensajes: 3
Antigüedad: 12 años, 9 meses
Puntos: 0
Respuesta: importar y exportar a Excel : Visual Basic 2005

Intenta con lo siguiente:

Dim fila As DataRow = tuDataSet.Tables("tabla").NewRow()
fila("campo1") = varX
fila("campo2") = Trim(textBox.Text)
fila("Campo_n") = Trim(textBox.Text)
tuDataSet.Tables("tabla").Rows.Add(fila)

Al estar enlazados el Dataset y el Grid, el grid se actualizaria automaticamente
  #4 (permalink)  
Antiguo 09/08/2011, 17:29
Avatar de moradazo  
Fecha de Ingreso: julio-2008
Ubicación: [email protected]
Mensajes: 355
Antigüedad: 15 años, 10 meses
Puntos: 2
Respuesta: importar y exportar a Excel : Visual Basic 2005

Hola muchisimas gracias por la ayuda. Resulta que ingreso su código a un botón, ahi disculpa la ignorancia, cuando dices "tuDataSet.Tables("tabla").NewRow(), eso lo debo dejar así o se supone que debo reemplazarlo por algún nombre que tenga en el programa?

Lo hice exactamente así, sin embargo cuando oprimo el botón agregar, se me cierra el programa.

Así dejé el código:
Código vb:
Ver original
  1. Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click, DataGridView1.AllowUserToAddRowsChanged
  2.         Dim fila As DataRow = MiDataSet.Tables("tabla").NewRow()
  3.         fila(0) = tb_citrix.Text
  4.         fila(1) = tb_nombre.Text
  5.         fila(2) = tb_hora.Text
  6.         fila(3) = tb_msisdn.Text
  7.         fila(4) = tb_razon.Text
  8.         fila(5) = tb_otros.Text
  9.     End Sub
  #5 (permalink)  
Antiguo 10/08/2011, 17:43
Avatar de moradazo  
Fecha de Ingreso: julio-2008
Ubicación: [email protected]
Mensajes: 355
Antigüedad: 15 años, 10 meses
Puntos: 2
Respuesta: importar y exportar a Excel : Visual Basic 2005

Por favor como agrego una fila a un datagrid dinámico. La fórmula que me dio el amigo anteriormente lo he cambiado de varias maneras y no encuentro forma.

Etiquetas: basic, bd, datagridview, excel, sql, visual
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:18.