900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > C# 从Excel复制数据粘贴到DataGridView的实现

C# 从Excel复制数据粘贴到DataGridView的实现

时间:2021-12-19 16:07:17

相关推荐

C# 从Excel复制数据粘贴到DataGridView的实现

实现目标:将Excel中复制到粘贴板的数据粘贴到DataGridView中

先上代码再说明:

private void dataGridView1_KeyPress_1(object sender, KeyPressEventArgs e){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 < clipboardText.Length; i++){if (clipboardText.Substring(i, 1) == "\t"){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 < rownum; i++){temp[i] = new String[colnum];}int m = 0, n = 0, len = 0;while (len != clipboardText.Length) {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 < selectedRowIndex + rownum; i++){for(int j = selectedColIndex; j < selectedColIndex + colnum; j++){this.dataGridView1.Rows[i].Cells[j].Value = temp[i - selectedRowIndex][j - selectedColIndex];}}}

1. Excel内容在粘贴板上的表示形式以及获取

粘贴板上的内容可以用以下方法直接获取。

string clipboardText = Clipboard.GetText();

获取到的String字符串包括了所有原Excel中的内容,每行中相邻单元格使用 " \t " 分隔,每一行最后一个单元格结束跟随着 " \n " 。

所以小Sa选择遍历获取的字符串,统计其中的 " \n " 和 " \t " 数量。显而易见地," \n " 的数量就是行数," \t " 的数量是 行数×(列数 - 1)。可以轻易确定粘贴内容的行列数。

2. 检测复制内容是否超出范围

在获取粘贴内容的行数和列数后,需要确定是就是粘贴是否会使内容超出DataGridView的范围。具体的实现方法就是确定当前选中单元格的行数和列数,分别加上复制内容的行数和列数,看是否超限。

3. 分隔复制内容

用二维数组还原单元格内容

4. 覆盖DataGridView对应内容

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。