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 originalImports System.Data.SqlClient
Imports System.Data.OleDb
Public Class Form1
Inherits System.Windows.Forms.Form
Private MiDataSet As New DataSet()
Private MiEnlazador As New BindingSource
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim abrir As New OpenFileDialog
abrir.Filter = "Archivo de excel|*.xls"
If abrir.ShowDialog = Windows.Forms.DialogResult.OK Then
importexcel(abrir.FileName)
End If
End Sub
Private Sub importexcel(ByVal path As String)
Dim sconnectionstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" + path + "" _
& ";" & "Extended Properties=Excel 8.0;"
Dim objconn As New OleDb.OleDbConnection(sconnectionstring)
objconn.Open()
Dim objcmdselect As New OleDb.OleDbCommand("SELECT * FROM [Hoja1$]", objconn)
Dim objadapter1 As New OleDb.OleDbDataAdapter()
objadapter1.SelectCommand = objcmdselect
Dim objdataset1 As New DataSet()
objadapter1.Fill(objdataset1, "XLData")
Me.DataGridView1.DataSource = objdataset1.Tables(0).DefaultView
objconn.Close()
End Sub
Public Sub exportaraexcel(ByVal dgv As DataGridView, ByVal pth As String)
Dim xlapp As Object = createobject("Excel.Application")
Dim xlwb As Object = xlapp.workbooks.add
Dim xlws As Object = xlwb.Worksheets(1)
For C As Integer = 0 To datagridview1.columns.count - 1
xlws.cells(1, c + 1).value = Datagridview1.columns(c).headertext
Next
For r As Integer = 0 To datagridview1.rowcount - 1
For c As Integer = 0 To datagridview1.columns.count - 1
xlws.cells(r + 2, c + 1).Value = datagridview1.item(c, r).Value
Next
Next
xlwb.saveas(pth)
xlws = Nothing
xlwb = Nothing
xlapp.quit()
xlapp = Nothing
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim save As New SaveFileDialog
save.Filter = "Archivo Excel | *.xls"
If save.ShowDialog = Windows.Forms.DialogResult.OK Then
exportaraexcel(Me.DataGridView1, save.FileName)
End If
End Sub