• 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('
    ');
                    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('	');
                            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. 代码如下:

  • 相关阅读:
    HDU 2883 kebab
    CSUOJ 1635 Restaurant Ratings
    CSUOJ 1638 Continued Fraction
    POJ 1852 Ants
    ZOJ 3471 Most Powerful
    CSUOJ 1637 Yet Satisfiability Again!
    如何生成CA证书
    Keepalived实现双机热备
    Nginx负载均衡的优缺点
    负载均衡之 nginx
  • 原文地址:https://www.cnblogs.com/dingshouqing/p/4011119.html
Copyright © 2020-2023  润新知