-
VB.Net中使用DataGrid载入Excel
我写这程序时,觉的以下几点需要注意(当时我不会写……看了网上朋友解答才会的):
1、在VB.Net中DataGrid.DataSource不接受Recordset,所以需要用Adapter.Fill(Dataset,Recordset,"TableName")将Recordset中的数据填充进Dataset。
2、用DataRow.Delete()删除行时,会出现DataGrid和Dataset索引不一致的现象(是因为DataGrid不是实表的原因吗?)。我删除行时,饶过索引问题,找到指定行的一个指定列字符,然后遍历Dataset找出指定字符所在的行,再删除那个行。
3、在导入Excel的时候,把它当数据库来导入,比用行和列填充容易,如果不当数据库来操作,就用Excel的组件。
请教各位朋友问题,谢谢:
1、如果实现导出Excel?
2、为什么Adapter.Update(Dataset,"Tablename")无法更新? 需要自动生成更新语句吗? 请详细解答,谢谢。
主要的类代码如下:
Class mine
Inherits Form1
Private oConn As Object
Private oRS As New ADODB.Recordset
Private mydata As New DataSet
Private myadpter As New OleDb.OleDbDataAdapter
Private err As String
Private myrow As DataRow
Private n As Integer
Private res As DialogResult
Private findkey As String
Public Sub findit(ByVal findkey As String)
Dim r As Integer
Dim l As Integer
For r = 0 To mydata.Tables("table").Rows.Count - 1
For l = 0 To mydata.Tables("table").Columns.Count - 1
If mydata.Tables("table").Rows(r).Item(l).ToString() = findkey Then
mydata.Tables("table").Rows(r).Item(l) = findkey
MessageBox.Show("找到指定数据,已经标记到行", "管理系统")
Form1.DataGrid1.CurrentRowIndex = r
Else
MessageBox.Show("没有找到数据", "管理系统")
End If
Next
Next
End Sub
Public Sub save()
Try
myadpter.Update(mydata, "table")
MessageBox.Show("保存成功", "管理系统")
Catch ex As Exception
MessageBox.Show("更新失败", "管理系统")
End Try
End Sub
Public Sub getkey()
findkey = InputBox("请输入需要查找的关键字", "管理系统")
findit(findkey)
End Sub
Public Sub getn()
n = Form1.DataGrid1.CurrentRowIndex()
End Sub
Public Sub getexcel(ByVal path As String, ByVal name As String)
Try
mydata.Clear()
oConn = CreateObject("ADODB.Connection")
oConn.CursorLocation = CursorLocationEnum.adUseClient
oConn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & path & ";Extended Properties='Excel 8.0'")
oRS.Open("Select * from [" & name & "$]", oConn, 3, 2)
myadpter.Fill(mydata, oRS, "table")
Form1.DataGrid1.DataSource = mydata.Tables("table")
Catch
err = InputBox("未找到默认工作表,请输入工作表名称:", "管理系统")
getexcel(Form1.fpath, err)
End Try
End Sub
Public Sub addrow()
mydata.Tables("table").Rows.Add()
End Sub
Public Sub delrow()
Dim i As Integer
res = MessageBox.Show("您是否确定要删除第" & n + 1 & "行?", "管理系统", MessageBoxButtons.YesNo)
If res = System.Windows.Forms.DialogResult.Yes Then
For i = 0 To mydata.Tables("table").Rows.Count - 1
Try
If mydata.Tables("table").Rows(i).Item(0) = Form1.DataGrid1.Item(n, 0) Then
mydata.Tables("table").Rows(i).Delete()
Exit Sub
End If
Catch
GoTo bug
End Try
bug:
Next
Else
End If
End Sub
End Class
出处:https://www.cnblogs.com/wmw1989/archive/2008/05/24/1206312.html