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放在任何位置都行。

相关推荐
穿西装的水獭3 小时前
python将Excel数据写进图片中
开发语言·python·excel
老友@4 小时前
Java Excel 导出:EasyExcel 使用详解
java·开发语言·excel·easyexcel·excel导出
郏国上12 小时前
查询数据库上所有表用到图片和视频的数据,并记录到excel表
mongodb·node.js·excel
OICQCO12 小时前
WPS Excel 图表
excel·wps
装不满的克莱因瓶12 小时前
【项目亮点】基于EasyExcel + 线程池解决POI文件导出时的内存溢出及超时问题
java·jvm·excel·线程池·async·虚拟机·easyexcel
njsgcs13 小时前
excel提取长宽,进行排版导出ezdxf 装箱算法 贪婪 总利用率91%
开发语言·python·excel
郏国上16 小时前
遍历访问阿里云节点下的所有文件信息并写入excel文件
数据库·mongodb·阿里云·excel
mudtools17 小时前
.NET驾驭Excel之力:Excel应用程序的创建与管理
c#·.net·excel·wps
mudtools17 小时前
.NET驾驭Excel之力:自动化数据处理 - 开篇概述与环境准备
c#·自动化·.net·excel·wps