源自http://www.51aspx.com/DownloadAuth/EBGHStickDateGridView/44369?needType=0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
// 下载于www.51aspx.com
namespace excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 9; i++)
{
dgvExcel.Rows.Add();
}
}
private void dgvExcel_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 22)
{
PasteData();
}
}
private void PasteData()
{
try
{
string clipboardText = Clipboard.GetText(); //获取剪贴板中的内容
if (string.IsNullOrEmpty(clipboardText))
{
return;
}
int colnum = 0;
int rownum = 0;
for (int i = 0; i < clipboardText.Length; i++)
{
if (clipboardText.Substring(i, 1) == "\t")
{
colnum++;
}
if (clipboardText.Substring(i, 1) == "\n")
{
rownum++;
}
}
//粘贴板上的数据来源于EXCEL时,每行末尾都有\n,来源于DataGridView是,最后一行末尾没有\n
if (clipboardText.Substring(clipboardText.Length - 1, 1) == "\n")
{
rownum--;
}
colnum = colnum / (rownum + 1);
object[,] data; //定义object类型的二维数组
data = new object[rownum + 1, colnum + 1]; //根据剪贴板的行列数实例化数组
string rowStr = "";
//对数组各元素赋值
for (int i = 0; i <= rownum; i++)
{
for (int j = 0; j <= colnum; j++)
{
//一行中的其它列
if (j != colnum)
{
rowStr = clipboardText.Substring(0, clipboardText.IndexOf("\t"));
clipboardText = clipboardText.Substring(clipboardText.IndexOf("\t") + 1);
}
//一行中的最后一列
if (j == colnum && clipboardText.IndexOf("\r") != -1)
{
rowStr = clipboardText.Substring(0, clipboardText.IndexOf("\r"));
}
//最后一行的最后一列
if (j == colnum && clipboardText.IndexOf("\r") == -1)
{
rowStr = clipboardText.Substring(0);
}
data[i, j] = rowStr;
}
//截取下一行及以后的数据
clipboardText = clipboardText.Substring(clipboardText.IndexOf("\n") + 1);
}
clipboardText = Clipboard.GetText();
int cellsCount = dgvExcel.SelectedCells.Count;
int r1 = (dgvExcel.SelectedCells[cellsCount - 1].RowIndex);
int r2 = (dgvExcel.SelectedCells[0].RowIndex);
int c1 = (dgvExcel.SelectedCells[cellsCount - 1].ColumnIndex);
int c2 = (dgvExcel.SelectedCells[0].ColumnIndex);
int rowIndex = Math.Abs(r2 - r1) + 1;
int colIndex = Math.Abs(c2 - c1) + 1;
if (colIndex != colnum + 1 || rowIndex != rownum + 1)
{
MessageBox.Show("粘贴区域大小不一致");
return;
}
else
{
for (int i = 0; i <= rownum; i++)
{
for (int j = 0; j <= colnum; j++)
{
dgvExcel.Rows[i + r1].Cells[j + c1].Value = data[i, j];
}
}
}
}
catch
{
MessageBox.Show("粘贴区域大小不一致");
return;
}
}
}
}