当前位置: 首页 > article >正文

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

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

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

    Private Sub DataGridView1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragEnterIf e.Data.GetDataPresent(DataFormats.FileDrop) ThenDim 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)) Thene.Effect = DragDropEffects.CopyEnd IfEnd IfEnd SubPrivate Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragDropTryDim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())If files IsNot Nothing AndAlso files.Length > 0 ThenDim excelPath = files(0)If String.Equals(Path.GetExtension(excelPath), ".xlsx", StringComparison.OrdinalIgnoreCase) ThenReadExcelToDataGridView(excelPath)ElseMessageBox.Show("仅支持.xlsx格式的Excel文件")End IfEnd IfCatch ex As ExceptionMessageBox.Show("处理失败:{0}" & ex.Message)End TryEnd 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)Tryconnection.Open()Dim sheetName = GetExcelSheetName(connection)If String.IsNullOrEmpty(sheetName) ThenMessageBox.Show("无法获取Excel工作表名称")ReturnEnd If'这里指定要读取excel的工作表标签名为sheetNameDim 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 - 1Dim 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 = NothingIf Not String.IsNullOrEmpty(imgPath) AndAlso File.Exists(imgPath) Thenimg = Image.FromFile(imgPath)Elseimg = My.Resources.NoImage  ' 需要在项目中添加默认图片资源End IfDataGridView1.Rows.Add(id, name, img)NextCatch ex As ExceptionMessageBox.Show("读取Excel失败:{ex.Message}")End TryEnd UsingEnd Sub' 获取Excel第一个工作表名称Private Function GetExcelSheetName(ByVal connection As OleDbConnection) As StringTryDim dataTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)If dataTable IsNot Nothing AndAlso dataTable.Rows.Count > 0 ThenReturn dataTable.Rows(0)("TABLE_NAME").ToString()End IfReturn String.EmptyCatchReturn String.EmptyEnd TryEnd Function

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

5、最终效果

6、完整代码如下:

Imports System.IO
Imports System.Windows.Forms
Imports System.Data.OleDb  ' 使用OLEDB访问ExcelPublic Class Form3Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load' 初始化DataGridViewDataGridView1.AllowDrop = TrueDataGridView1.Columns.Add("ID", "编号")DataGridView1.Columns.Add("Name", "名称")' 添加图片列Dim imgCol As New DataGridViewImageColumnimgCol.HeaderText = "图片"imgCol.ImageLayout = DataGridViewImageCellLayout.ZoomDataGridView1.Columns.Add(imgCol)End SubPrivate Sub DataGridView1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragEnterIf e.Data.GetDataPresent(DataFormats.FileDrop) ThenDim 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)) Thene.Effect = DragDropEffects.CopyEnd IfEnd IfEnd SubPrivate Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles DataGridView1.DragDropTryDim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())If files IsNot Nothing AndAlso files.Length > 0 ThenDim excelPath = files(0)If String.Equals(Path.GetExtension(excelPath), ".xlsx", StringComparison.OrdinalIgnoreCase) ThenReadExcelToDataGridView(excelPath)ElseMessageBox.Show("仅支持.xlsx格式的Excel文件")End IfEnd IfCatch ex As ExceptionMessageBox.Show("处理失败:{0}" & ex.Message)End TryEnd 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)Tryconnection.Open()Dim sheetName = GetExcelSheetName(connection)If String.IsNullOrEmpty(sheetName) ThenMessageBox.Show("无法获取Excel工作表名称")ReturnEnd If'这里指定要读取excel的工作表标签名为sheetNameDim 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 - 1Dim 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 = NothingIf Not String.IsNullOrEmpty(imgPath) AndAlso File.Exists(imgPath) Thenimg = Image.FromFile(imgPath)Elseimg = My.Resources.NoImage  ' 需要在项目中添加默认图片资源End IfDataGridView1.Rows.Add(id, name, img)NextCatch ex As ExceptionMessageBox.Show("读取Excel失败:{ex.Message}")End TryEnd UsingEnd Sub' 获取Excel第一个工作表名称Private Function GetExcelSheetName(ByVal connection As OleDbConnection) As StringTryDim dataTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)If dataTable IsNot Nothing AndAlso dataTable.Rows.Count > 0 ThenReturn dataTable.Rows(0)("TABLE_NAME").ToString()End IfReturn String.EmptyCatchReturn String.EmptyEnd TryEnd Function
End Class

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

http://www.lryc.cn/news/2385039.html

相关文章:

  • 跨域_Cross-origin resource sharing
  • Opencv常见学习链接(待分类补充)
  • 大疆制图跑飞马D2000的正射与三维模型
  • PostgreSQL中的权限管理简介
  • ConceptAttention:Diffusion Transformers learn highly interpretable features
  • 物联网低功耗保活协同优化方案:软硬件与WiFi网关动态联动
  • LW-CTrans:一种用于三维医学图像分割的轻量级CNN与Transformer混合网络|文献速递-深度学习医疗AI最新文献
  • 光谱相机在地质勘测中的应用
  • Autodl训练Faster-RCNN网络(自己的数据集)
  • 每日两道leetcode(今天开始刷基础题模块——这次是之前的修改版)
  • 服务器数据迁移终极指南:网站、数据库、邮件无缝迁移策略与工具实战 (2025)
  • NFS服务小实验
  • vue 中的v-once
  • 鸿蒙ArkTS-发请求第三方接口显示实时新闻列表页面
  • 2025年开源大模型技术全景图
  • 【创造型模式】工厂方法模式
  • 【MySQL】使用文件进行交互
  • # 大模型的本地部署与应用:从入门到实战
  • 布丁扫描高级会员版 v3.5.2.2| 安卓智能扫描 APP OCR文字识别小助手
  • 可视化大屏全屏后重载echarts图表
  • 20200201工作笔记常用命令要整理
  • Java对象内存模型、如何判定对象已死亡?
  • spark任务的提交流程
  • ELK简介和docker版安装
  • 利用条件编译实现RTT可控的调试输出
  • 【软件设计师】计算机网络考点整理
  • 智慧化工园区安全风险管控平台建设方案(Word)
  • 【uniapp】 iosApp开发xcode原生配置项(iOS平台Capabilities配置)
  • MYSQL优化(1)
  • C++可变参数宏定义语法笔记