DataGridView中拖放带有图片的Excel,实现数据批量导入

1、带有DataGridView的窗体,界面如下

2、编写DataGridView支持拖放的代码

vbnet 复制代码
    Private Sub DataGridView1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
            If files IsNot Nothing AndAlso files.Any(Function(f) _
                String.Equals(Path.GetExtension(f), ".xlsx", StringComparison.OrdinalIgnoreCase)) Then
                e.Effect = DragDropEffects.Copy
            End If
        End If
    End Sub

    Private Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragDrop
        Try
            Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
            If files IsNot Nothing AndAlso files.Length > 0 Then
                Dim excelPath = files(0)
                If String.Equals(Path.GetExtension(excelPath), ".xlsx", StringComparison.OrdinalIgnoreCase) Then
                    ReadExcelToDataGridView(excelPath)
                Else
                    MessageBox.Show("仅支持.xlsx格式的Excel文件")
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("处理失败:{0}" & ex.Message)
        End Try
    End Sub

3、使用OLEDB读取Excel文件

vbnet 复制代码
' 使用OLEDB读取Excel文件
    Private Sub ReadExcelToDataGridView(ByVal excelPath As String)
        DataGridView1.Rows.Clear()
        Dim connectionString As String = String.Format(
            "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""",
            excelPath)

        Using connection As New OleDbConnection(connectionString)
            Try
                connection.Open()
                Dim sheetName = GetExcelSheetName(connection)
                If String.IsNullOrEmpty(sheetName) Then
                    MessageBox.Show("无法获取Excel工作表名称")
                    Return
                End If

                '这里指定要读取excel的工作表标签名为sheetName
                Dim query = String.Format("SELECT * FROM [{0}]", sheetName)
                Dim adapter As New OleDbDataAdapter(query, connection)
                Dim dataTable As New DataTable()
                adapter.Fill(dataTable)

                ' 填充DataGridView(跳过标题行)
                For i As Integer = 0 To dataTable.Rows.Count - 1
                    Dim row = dataTable.Rows(i)
                    Dim id = If(IsDBNull(row(0)), "", row(0).ToString())
                    Dim name = If(IsDBNull(row(1)), "", row(1).ToString())
                    Dim imgPath = If(IsDBNull(row(2)), "", row(2).ToString())

                    Dim img As Image = Nothing
                    If Not String.IsNullOrEmpty(imgPath) AndAlso File.Exists(imgPath) Then
                        img = Image.FromFile(imgPath)
                    Else
                        img = My.Resources.NoImage  ' 需要在项目中添加默认图片资源
                    End If

                    DataGridView1.Rows.Add(id, name, img)
                Next
            Catch ex As Exception
                MessageBox.Show("读取Excel失败:{ex.Message}")
            End Try
        End Using
    End Sub

    ' 获取Excel第一个工作表名称
    Private Function GetExcelSheetName(ByVal connection As OleDbConnection) As String
        Try
            Dim dataTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
            If dataTable IsNot Nothing AndAlso dataTable.Rows.Count > 0 Then
                Return dataTable.Rows(0)("TABLE_NAME").ToString()
            End If
            Return String.Empty
        Catch
            Return String.Empty
        End Try
    End Function

4、创建一个Excel文件,这里要求为Excel第一个工作表

5、最终效果

6、完整代码如下:

vbnet 复制代码
Imports System.IO
Imports System.Windows.Forms
Imports System.Data.OleDb  ' 使用OLEDB访问Excel

Public Class Form3
    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        ' 初始化DataGridView
        DataGridView1.AllowDrop = True
        DataGridView1.Columns.Add("ID", "编号")
        DataGridView1.Columns.Add("Name", "名称")

        ' 添加图片列
        Dim imgCol As New DataGridViewImageColumn
        imgCol.HeaderText = "图片"
        imgCol.ImageLayout = DataGridViewImageCellLayout.Zoom
        DataGridView1.Columns.Add(imgCol)
    End Sub

    Private Sub DataGridView1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
            If files IsNot Nothing AndAlso files.Any(Function(f) _
                String.Equals(Path.GetExtension(f), ".xlsx", StringComparison.OrdinalIgnoreCase)) Then
                e.Effect = DragDropEffects.Copy
            End If
        End If
    End Sub

    Private Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragDrop
        Try
            Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
            If files IsNot Nothing AndAlso files.Length > 0 Then
                Dim excelPath = files(0)
                If String.Equals(Path.GetExtension(excelPath), ".xlsx", StringComparison.OrdinalIgnoreCase) Then
                    ReadExcelToDataGridView(excelPath)
                Else
                    MessageBox.Show("仅支持.xlsx格式的Excel文件")
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("处理失败:{0}" & ex.Message)
        End Try
    End Sub

    ' 使用OLEDB读取Excel文件
    Private Sub ReadExcelToDataGridView(ByVal excelPath As String)
        DataGridView1.Rows.Clear()
        Dim connectionString As String = String.Format(
            "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""",
            excelPath)

        Using connection As New OleDbConnection(connectionString)
            Try
                connection.Open()
                Dim sheetName = GetExcelSheetName(connection)
                If String.IsNullOrEmpty(sheetName) Then
                    MessageBox.Show("无法获取Excel工作表名称")
                    Return
                End If

                '这里指定要读取excel的工作表标签名为sheetName
                Dim query = String.Format("SELECT * FROM [{0}]", sheetName)
                Dim adapter As New OleDbDataAdapter(query, connection)
                Dim dataTable As New DataTable()
                adapter.Fill(dataTable)

                ' 填充DataGridView(跳过标题行)
                For i As Integer = 0 To dataTable.Rows.Count - 1
                    Dim row = dataTable.Rows(i)
                    Dim id = If(IsDBNull(row(0)), "", row(0).ToString())
                    Dim name = If(IsDBNull(row(1)), "", row(1).ToString())
                    Dim imgPath = If(IsDBNull(row(2)), "", row(2).ToString())

                    Dim img As Image = Nothing
                    If Not String.IsNullOrEmpty(imgPath) AndAlso File.Exists(imgPath) Then
                        img = Image.FromFile(imgPath)
                    Else
                        img = My.Resources.NoImage  ' 需要在项目中添加默认图片资源
                    End If

                    DataGridView1.Rows.Add(id, name, img)
                Next
            Catch ex As Exception
                MessageBox.Show("读取Excel失败:{ex.Message}")
            End Try
        End Using
    End Sub

    ' 获取Excel第一个工作表名称
    Private Function GetExcelSheetName(ByVal connection As OleDbConnection) As String
        Try
            Dim dataTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
            If dataTable IsNot Nothing AndAlso dataTable.Rows.Count > 0 Then
                Return dataTable.Rows(0)("TABLE_NAME").ToString()
            End If
            Return String.Empty
        Catch
            Return String.Empty
        End Try
    End Function
End Class

最后说明,Excel中如果使用图片的绝对路径,Excel放在任何位置都行。

相关推荐
揭老师高效办公2 天前
在Excel和WPS表格中拼接同行列对称的不连续数据
excel·wps表格
用户0332126663672 天前
Java 设置 Excel 行高列宽:告别手动调整,拥抱自动化高效!
java·excel
专注VB编程开发20年2 天前
.NET组件读取压缩包中的内存数据电子表格XLSX文件和图片,不需要解压
linux·服务器·windows·c#·.net·excel·zip
菌王2 天前
EXCEL自动调整列宽适应A4 A3 A2
excel
专注VB编程开发20年3 天前
对excel xlsx文件格式当成压缩包ZIP添加新的目录和文件后,OpenXml、NPOI、EPPlus、Spire.Office组件还能读出来吗
数据库·c#·excel
用户0332126663673 天前
Java 将 CSV 转换为 Excel:告别繁琐,拥抱高效数据处理
java·excel
lijingguang3 天前
excel 破解工作表密码
excel
我命由我123453 天前
Excel 表格 - 合并单元格、清除单元格格式
运维·word·powerpoint·excel·工具·表格·软件工具
专注VB编程开发20年3 天前
OpenXml、NPOI、EPPlus、Spire.Office组件对EXCEL ole对象附件的支持
前端·.net·excel·spire.office·npoi·openxml·spire.excel
程序视点4 天前
「Excel文件批量加密与合并工具推荐」高效办公必备神器 - 程序视点
excel