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

相关推荐
xzdangelliu3 小时前
POI模板生成EXCEL 64000 style in a .xlsx Workbook
java·excel·poi
编程乐趣3 小时前
推荐一个Excel与实体映射导入导出的C#开源库
开源·c#·.net·excel
开开心心就好9 小时前
小巧高效的目录索引生成软件
javascript·python·智能手机·django·pdf·word·excel
沉到海底去吧Go11 小时前
【身份证识别表格】把大量手机拍摄的身份证信息转换成EXCEL表格的数据,拍的身份证照片转成excel表格保存,基于WPF和腾讯OCR的实现方案
ocr·wpf·excel
兔子蟹子11 小时前
JAVA Apache POI实战:从基础Excel导出入门到高级功能拓展
java·apache·excel
灏瀚星空12 小时前
Python开发Excel批量写入工具:多文件独立配置与Tkinter界面设计
开发语言·python·excel
洛可可白16 小时前
Vue2实现Office文档(docx、xlsx、pdf)在线预览
javascript·vue.js·pdf·word·excel·office
五步晦暝1 天前
【Excel VBA 】窗体控件分类
excel
未来之窗软件服务1 天前
在 Excel xll 自动注册操作 中使用东方仙盟软件————仙盟创梦IDE
excel·excel插件·仙盟创梦ide
Smilecoc2 天前
数据透视表和公式法在Excel中实现去除重复计数的方法
excel