C# 复制粘贴板 多行粘贴

Demo:

public void DataGirdViewCellPaste()
{
try
{
// 获取剪切板的内容,并按行分割
string pasteText = "";
pasteText = Clipboard.GetText();

if (string.IsNullOrEmpty(pasteText))
return;
if (pasteText == "pasteText")
{
return;
}
int tnum = 0;
int nnum = 0;
//获得当前剪贴板内容的行、列数
for (int i = 0; i < pasteText.Length; i++)
{
if (pasteText.Substring(i, 1) == " ")
{
tnum++;
}
if (pasteText.Substring(i, 1) == " ")
{
nnum++;
}
}
Object[,] data;
//粘贴板上的数据来自于EXCEL时,每行末都有 ,在DATAGRIDVIEW内复制时,最后一行末没有
if (pasteText.Substring(pasteText.Length - 1, 1) == " ")
{
nnum = nnum - 1;
}
tnum = tnum / (nnum + 1);
data = new object[nnum + 1, tnum + 1];//定义一个二维数组

String rowstr;
rowstr = "";
//MessageBox.Show(pasteText.IndexOf("B").ToString());
//对数组赋值
for (int i = 0; i < (nnum + 1); i++)
{
for (int colIndex = 0; colIndex < (tnum + 1); colIndex++)
{
//一行中的最后一列
if (colIndex == tnum && pasteText.IndexOf(" ") != -1)
{
rowstr = pasteText.Substring(0, pasteText.IndexOf(" "));
}
//最后一行的最后一列
if (colIndex == tnum && pasteText.IndexOf(" ") == -1)
{
rowstr = pasteText.Substring(0);
}
//其他行列
if (colIndex != tnum)
{
rowstr = pasteText.Substring(0, pasteText.IndexOf(" "));
pasteText = pasteText.Substring(pasteText.IndexOf(" ") + 1);
}
data[i, colIndex] = rowstr;
}
//截取下一行数据
pasteText = pasteText.Substring(pasteText.IndexOf(" ") + 1);
}
//获取当前选中单元格所在的列序号
int curntindex = skinDataGridView1.SelectedCells[0].ColumnIndex;
//获取获取当前选中单元格所在的行序号
int rowindex = skinDataGridView1.SelectedCells[0].RowIndex;
//MessageBox.Show(curntindex.ToString ());
for (int j = 0; j < (nnum + 1); j++)
{
for (int colIndex = 0; colIndex < (tnum + 1); colIndex++)
{
if (!skinDataGridView1.Columns[colIndex + curntindex].Visible)
{
continue;
}
if (!skinDataGridView1.Rows[j + rowindex].Cells[colIndex + curntindex].ReadOnly)
{
skinDataGridView1.Rows[j + rowindex].Cells[colIndex + curntindex].Value = data[j, colIndex];
}
}
}
//Clipboard.Clear();
}
catch
{
//Clipboard.Clear();
//MessageBox.Show("粘贴区域大小不一致");
return;
}
}

转载自:https://bbs.csdn.net/topics/360108393