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

news2025/5/25 2:37:52

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

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

    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文件

' 使用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、完整代码如下:

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2385039.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

跨域_Cross-origin resource sharing

同源是指"协议域名端口"三者相同,即便两个不同的域名指向同一个ip,也非同源 1.什么是CORS? CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器&#xff…

Opencv常见学习链接(待分类补充)

文章目录 1.常见学习链接 1.常见学习链接 1.Opencv中文官方文档 2.Opencv C图像处理:矩阵Mat 随机数RNG 计算耗时 鼠标事件 3.Opencv C图像处理:亮度对比度饱和度高光暖色调阴影漫画效果白平衡浮雕羽化锐化颗粒感 4.OpenCV —— 频率域滤波&#xff…

大疆制图跑飞马D2000的正射与三维模型

1 问题描述 大疆制图在跑大疆无人机飞的影像的时候,能够自动识别相机参数并且影像自带pos信息,但是用飞马无人机获取的影像pos信息与影像是分开的(飞马无人机数据处理有讲),所以在用大疆制图时需要对相机参数进行设置…

ConceptAttention:Diffusion Transformers learn highly interpretable features

ConceptAttention: Diffusion Transformers Learn Highly Interpretable Featureshttps://arxiv.org/html/2502.04320?_immersive_translate_auto_translate=1用flux的attention来做图文的显著性分析。 1.i

物联网低功耗保活协同优化方案:软硬件与WiFi网关动态联动

目录 一、总体方案概述 二、架构组成 2.1 系统拓扑 2.2 硬件端(MCU + WiFi 模组) 2.3 WiFi 网关 2.4 云端服务器 三、低功耗保活技术设计模式 3.1 模式一:定时唤醒 + MQTT 保活 3.1.1 设备端 3.1.2 优势 3.2 模式二:网关保活代理 + 本地网络唤醒 3.2.1 网关功能…

LW-CTrans:一种用于三维医学图像分割的轻量级CNN与Transformer混合网络|文献速递-深度学习医疗AI最新文献

Title 题目 LW-CTrans: A lightweight hybrid network of CNN and Transformer for 3Dmedical image segmentation LW-CTrans:一种用于三维医学图像分割的轻量级CNN与Transformer混合网络 01 文献速递介绍 三维医学图像分割旨在从计算机断层扫描(CT…

光谱相机在地质勘测中的应用

一、‌矿物识别与蚀变带分析‌ ‌光谱特征捕捉‌ 通过可见光至近红外(400-1000nm)的高光谱分辨率(可达3.5nm),精确识别矿物的“光谱指纹”。例如: ‌铜矿‌:在400-500nm波段反射率显著低于围…

Autodl训练Faster-RCNN网络(自己的数据集)

参考文章: Autodl服务器中Faster-rcnn(jwyang)复现(一)_autodl faster rcnn-CSDN博客 Autodl服务器中Faster-rcnn(jwyang)训练自己数据集(二)_faster rcnn autodl-CSDN博客 环境配置 我到下载torch这一步老是即将结束的时候自动结束进程,所以还是自己…

NFS服务小实验

实验1 建立NFS服务器,使的客户端顺序共享数据 第一步:服务端及客户端的准备工作 # 恢复快照 [rootserver ~]# setenforce 0 ​ [rootserver ~]# systemctl stop firewalld ​ [rootserver ~]# yum install nfs-utils -y # 服务端及客户端都安装 …

鸿蒙ArkTS-发请求第三方接口显示实时新闻列表页面

发请求展示新闻列表 鸿蒙ArkTS-发请求第三方接口显示实时新闻列表页面 1. 效果图 新闻首页: 点击某一新闻的详情页面(需要使用模拟器才能查看详情页面): 2. 代码 1. key准备 首先需求到聚合网申请一个key,网址如下…

【创造型模式】工厂方法模式

文章目录 工厂方法模式工厂方法模式当中的角色和职责工厂方法模式的实现工厂方法模式的优缺点 工厂方法模式 今天我们继续学习一例创造型设计模式——工厂方法模式。参考的主要资料是刘丹冰老师的《Easy 搞定 Golang 设计模式》。 工厂方法模式当中的角色和职责 简单来说&…

【MySQL】使用文件进行交互

目录 准备工作 1.从文本文件中读取数据(导入) 1.1.CSV 文件 1.2.设置导入导出的路径 1.3.导入文件 1.4.将数据写入文本文件(导出) 2.从文件中读取并执行SQL命令 2.1.通过mysql监视器执行编写在文件里面的SQL语句 2.2.通过…

# 大模型的本地部署与应用:从入门到实战

大模型的本地部署与应用:从入门到实战 在当今人工智能飞速发展的时代,大模型(尤其是大型语言模型,LLMs)已经成为自然语言处理(NLP)领域的核心力量。从文本生成、机器翻译到问答系统&#xff0c…

Java对象内存模型、如何判定对象已死亡?

一、Java对象内存模型 Java对象在内存中由三部分组成: 含类元数据指针(指向方法区的Class对象)和Mark Word(存储对象哈希码、锁状态、GC分代年龄等信息)。 若为数组对象,还包含数组长度数据。 1&#xff0c…

智慧化工园区安全风险管控平台建设方案(Word)

1 项目概况 1.1 园区概况 1.1.1 XX化工园区简况 1.1.2 企业现状 1.1.3 园区发展方向 1.1.4 园区信息化现状 1.2 项目建设背景 1.2.1 政策背景 1.3 项目建设需求分析 1.3.1 政策需求分析 1.3.2 安全生产监管需求分析 1.3.3 应急协同管理需求分析 1.3.4 工业互联网安…

【uniapp】 iosApp开发xcode原生配置项(iOS平台Capabilities配置)

如果你需要配置诸如:Access Wi-Fi Information 简单地说就是这个地址 ios平台capabilities配置 本来这种配置就是在Xcode的平台中选中即可,他们的信息会存储在XCode工程的.entitlements和Info.plist文件。 按照uniapp文档说的, HBuilderX4.…

MYSQL优化(1)

MYSQL调优强调的是如何提高MYSQL的整体性能,是一套整体方案。根据木桶原理,MYSQL的最终性能取决于系统中性能表现最差的组件。可以这样理解,即使MYSL拥有充足的内存资源,CPU资源,如果外存IO性能低下,那么系…

基于BERT预训练模型(bert_base_chinese)训练中文文本分类任务(AI老师协助编程)

新建项目 创建一个新的虚拟环境 创建新的虚拟环境(大多数时候都需要指定python的版本号才能顺利创建): conda create -n bert_classification python3.9激活虚拟环境: conda activate myenvPS:虚拟环境可以避免权限问题,并隔离…

从数据到智能:openGauss+openEuler Intelligence的RAG架构实战

随着人工智能和大规模语言模型技术的崛起,传统的搜索引擎由于其只能提供简单的关键字匹配结果,已经越来越无法满足用户对于复杂、多样化和上下文相关的知识检索需求。与此相对,RAG(Retrieval-Augmented Generation)技术…

【Linux】初见,基础指令

前言 本文将讲解Linux中最基础的东西-----指令,带大家了解一下Linux中有哪些基础指令,分别有什么作用。 本文中的指令和选项并不全,只介绍较为常用的 pwd指令 语法:pwd 功能:显示当前所在位置(路径&#xf…