Excel 内容粘贴到DataGridView, DataGridView 粘贴到 Excel

void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                DataObject d = dataGridView1.GetClipboardContent();
                Clipboard.SetDataObject(d);
                e.Handled = true;
            }
            else if (e.Control && e.KeyCode == Keys.V)
            {
                string s = Clipboard.GetText();
                string[] lines = s.Split('\n');
                int row = dataGridView1.CurrentCell.RowIndex;
                int col = dataGridView1.CurrentCell.ColumnIndex;
                
                //check if need add row
                if ((dataGridView1.Rows.Count - row) < lines.Length)
                {
                    dataGridView1.Rows.Add(lines.Length - (dataGridView1.Rows.Count - row));
                }

                foreach (string line in lines)
                {
                    if ((line.Length > 0) && row < dataGridView1.RowCount)
                    {
                        string[] cells = line.Split('\t');
                        for (int i = 0; i < cells.GetLength(0); ++i)
                        {
                            if (col + i < this.dataGridView1.ColumnCount)
                            {
                                dataGridView1[col + i, row].Value = Convert.ChangeType(cells[i], dataGridView1[col + i, row].ValueType);
                            }
                            else
                            {
                                break;
                            }
                        }
                        row++;
                    }
                    else if (row == dataGridView1.RowCount && line.Length > 0)
                    {
                        break;
                    }
                }
            }
        }

 将Excel中内容直接复制粘贴到DataGridView中或其他表格控件中(其他控件代码类似),将表格内容复制粘贴到Excel中.
实现CTRL+C 和CTRL+V. 代码如下:

posted @ 2014-10-08 14:24  丁守庆  阅读(1049)  评论(0编辑  收藏  举报
专业成就价值