excel和datagridview同根同源,有时候我们希望从excel中复制粘贴一些数据到datagridview中

界面设计

datagridview 粘贴复制

简单的一个datagridview  里面有四列

datagridview 粘贴复制

然后一个内嵌 菜单,关联上

keydown事件,以及粘贴和删除事件

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyValue == 86) 
            {
                ZhanTie();
            }
        }



        private void ZhanTie()
        {   
            //这里是取剪贴板里的内容,如果内容为空,则退出
            string pastTest = Clipboard.GetText();
            if (string.IsNullOrEmpty(pastTest)) return;
            //excel中是以 空格 和换行来 当做字段和行,所以用\n \r来分隔
            string[] lines = pastTest.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in lines)
            {
                string[] strs = line.Split(new char[] { '\t' });
                dataGridView1.Rows.Add(strs);
            }
        }

        private void PaestMenuItem_Click(object sender, EventArgs e)
        {
            ZhanTie();
        }

        private void DeleteMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null ||dataGridView1.CurrentRow.Index==dataGridView1.Rows.Count-1) return;

            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
        }
    }

代码经过vs2010测试通过,至于datagirdview的复制,你可以直接用ctrl+c复制到txt中

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-10-20
  • 2021-08-19
  • 2021-08-19
  • 2021-11-28
猜你喜欢
  • 2022-12-23
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-26
  • 2022-12-23
  • 2022-02-02
相关资源
相似解决方案