将Excel的内容复制到DataGridView中

示例代码如下:

private void dgv_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 22)
            {
                Thread thread = new Thread(new ThreadStart(PasteData));
                thread.SetApartmentState(ApartmentState.STA); //重点
                thread.Start();
                //PasteData();
            }
        }

        [STAThread]
        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.dgv.CurrentRow.Index;
            selectedColIndex = this.dgv.CurrentCell.ColumnIndex;
            if (selectedRowIndex + rownum > dgv.RowCount || selectedColIndex + colnum > dgv.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.dgv.Rows[i].Cells[j].Value = temp[i - selectedRowIndex][j - selectedColIndex];
                }
            }
        }
发布了30 篇原创文章 · 获赞 2 · 访问量 6603

猜你喜欢

转载自blog.csdn.net/tangliuqing/article/details/104924062