C#【必备技能篇】从Excel复制数据粘贴到DataGridView的代码实现 您所在的位置:网站首页 excel粘贴数值和格式的快捷键一样吗 C#【必备技能篇】从Excel复制数据粘贴到DataGridView的代码实现

C#【必备技能篇】从Excel复制数据粘贴到DataGridView的代码实现

2024-07-03 09:11| 来源: 网络整理| 查看: 265

文章目录 一、源码【Datagridview为10行3列】二、运行效果三、代码实现思路1)Excel内容在粘贴板上的表示形式以及获取2)检测复制内容是否超出范围3)分隔复制内容4)覆盖DataGridView对应内容

一、源码【Datagridview为10行3列】

在这里插入图片描述

using System; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e) { //在选定的单元格,如果按下Ctrl+V if (e.KeyChar == 22) { PasteData(); } } private void PasteData() { string clipboardText = Clipboard.GetText(); //获取剪贴板中的内容 if (string.IsNullOrEmpty(clipboardText)) { return; } int colnum = 0; int rownum = 0; for (int i = 0; i colnum++; } if (clipboardText.Substring(i, 1) == "\n") { rownum++; } } colnum = colnum / rownum + 1; int selectedRowIndex, selectedColIndex; selectedRowIndex = this.dataGridView1.CurrentRow.Index; selectedColIndex = this.dataGridView1.CurrentCell.ColumnIndex; if (selectedRowIndex + rownum > dataGridView1.RowCount || selectedColIndex + colnum > dataGridView1.ColumnCount) { MessageBox.Show("粘贴区域大小不一致"); return; } String[][] temp = new String[rownum][]; for (int i = 0; i String str = clipboardText.Substring(len, 1); if (str == "\t") { n++; } else if (str == "\n") { m++; n = 0; } else { temp[m][n] += str; } len++; } for (int i = selectedRowIndex; i this.dataGridView1.Rows[i].Cells[j].Value = temp[i - selectedRowIndex][j - selectedColIndex]; } } } private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有