vb.net 如何实现从EXCEL复制内容到datagridview内容?

vb.net 如何实现从EXCEL复制内容到datagridview内容?

3个回答

用 npoi 读取解析 excel,再加载到 datagridview 里

以下代码为我以前的工程代码,摘取读取excel数据到ListBox中的部分,改下应该就能到datagridview
注意代码中的:xlSheet.Cells(i, 2).Value,这就是excel单元格内的值
Imports Microsoft.Office.Interop
Imports System.Net.Mime.MediaTypeNames
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim TxtName As String
OpenFileDialog1.Filter = "xls files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
'check if selected
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
'get file path
TxtName = System.IO.Path.GetFullPath(OpenFileDialog1.FileName)
'Read Excel
Dim xlAppExcelFile As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim intColNum As Integer
Dim intRowNum As Integer
'生成新的instance
xlAppExcelFile = New Excel.Application
'在已有的Excel,指定文件路径,打开Book
xlBook = xlAppExcelFile.Workbooks.Open(TxtName)
'不显示Excel
xlAppExcelFile.Visible = False
'禁止显示对话框和警告消息
xlAppExcelFile.DisplayAlerts = False
'取消任务栏中的窗口选项
xlAppExcelFile.ShowWindowsInTaskbar = False
xlSheet = xlBook.Sheets(1)
intRowNum = xlSheet.UsedRange.Rows.Count
intColNum = xlSheet.UsedRange.Columns.Count
'所有行
For i = 2 To intRowNum
'Message
If xlSheet.Cells(i, 2).Value <> "" Then
ListBoxAllMessage.Items.Add(Replace(xlSheet.Cells(i, 2).Value, " ", ""))
End If
next
''终止excel操作
xlSheet = Nothing
xlBook.Close()
xlBook = Nothing
xlAppExcelFile.Quit()
xlAppExcelFile = Nothing

直接用ACE数据库引擎,以数据库方式读取EXCEL,又快又方便,读取到DataTable然后绑定给datagridview

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问