文章目录
一、源码【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 |