C# 完美实现DataGridView批量复制多行/单元格数据并粘贴功能

C#系统默认情况下不支持批量粘贴多行或多个单元格数据,但是有时想直接复制dataGridView的一部分数据,然后一起粘贴到DatagridView的指定位置。

关键步骤

0.创建一个C#窗体应用程序this,调用一个DataGridView控件this.dataGridView1

1.重写this.dataGridView1的ProcessCmdKey方法,获取键盘点击事件,识别Ctrl+V

2.获取剪贴板HTML数据并解析,将多行多列数据分别填至光标指定或选中的单元格中

3.清空消息参数,防止系统调用默认的剪贴功能,将复制的第一行数据不正确地填充至一个单元格中

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //在检测到按Ctrl+V键后,系统无法复制多单元格数据,重写ProcessCmdKey方法,屏蔽系统粘贴事件,使用自定义粘贴事件,在事件中对剪贴板的HTML格式进行处理,获取表数据,更新DataGrid控件内容
            if (keyData == (Keys.V| Keys.Control))  // &&
            {
                IDataObject idataObject = Clipboard.GetDataObject();
                string[] s = idataObject.GetFormats();
                string data;
                if (!s.Any(f=>f=="OEMText"))
                {
                    if (!s.Any(f=>f=="HTML Format"))
                    {
                    }
                    else
                    {
                        data = idataObject.GetData("HTML Format").ToString();//多个单元格
                        copyClipboardHtmltoGrid(data);
                        //msg = Message.;
                        msg = new Message();
                        return base.ProcessCmdKey(ref msg, Keys.Control);
                    }
                }else
                    data = idataObject.GetData("OEMText").ToString();//单个单元格,使用系统功能,无需处理
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

当复制单行数据时,剪贴板中没有HTML格式的数据,此时可获取OEMText格式的数据,或者不加处理,使用系统粘贴功能;

当复制多行时,可以通过解析剪贴板的HTML格式的数据,获取多个单元格的数据

关于Windows剪贴板数据格式的问题,可以参考我的上一篇博客

 

copyClipboardHtmltoGrid(data);方法识别剪贴板的HTML格式数据,并将结果动态地赋值给this.dataGridView1

private void copyClipboardHtmltoGrid(string data)
        {
            //截取出HTML内容
            int start, end = -1, index, rowStart = 0, columnStart = 0;
            Regex regex = new Regex(@"StartFragment:\d+");
            Match match = regex.Match(data);
            if (match.Success)
            {
                start = Convert.ToInt16(match.Value.Substring(14));
            }
            else
            {
                return;
            }
            regex = new Regex(@"EndFragment:\d+");
            match = regex.Match(data, match.Index + match.Length);
            if (match.Success)
            {
                end = Convert.ToInt16(match.Value.Substring(12));
            }
            else
            {
                return;
            }

            if (this.dataGridView1.SelectedCells.Count > 0)
            {
                rowStart = this.dataGridView1.SelectedCells[0].RowIndex;
                columnStart = this.dataGridView1.SelectedCells[0].ColumnIndex;
            }
            data = data.Substring(start, end - start);

            MatchCollection matchcollection = new Regex(@"<TR>[\S\s]*?</TR>").Matches(data), sub_matchcollection;
            int count = rowStart + matchcollection.Count - this.dataGridView1.RowCount;
            if (count>=0)
            {
                this.dataGridView1.Rows.Add(count+1);
            }
            for (int i = 0; i < matchcollection.Count && i + rowStart < this.dataGridView1.RowCount ; i++)
            {
                sub_matchcollection = new Regex(@"<TD>[\S\s]*?</TD>").Matches(matchcollection[i].Value);
                for (int j = 0; j < sub_matchcollection.Count && j + columnStart < this.dataGridView1.ColumnCount; j++)
                {
                    this.dataGridView1.Rows[i + rowStart].Cells[j + columnStart].Value = sub_matchcollection[j].Value.Substring(4, sub_matchcollection[j].Length - 9).Trim();
                }
            }
        }

效果截图: 

解决新问题

 问题1:处于编辑状态复制单元格数据,然后在选中非编辑状态单元格粘贴数据失败

 问题2:如果复制多个单元格数据中包含中文,则粘贴的时候出现乱码

修改ProcessCmdKey函数

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //在检测到按Ctrl+V键后,系统无法复制多单元格数据,重写ProcessCmdKey方法,屏蔽系统粘贴事件,使用自定义粘贴事件,在事件中对剪贴板的HTML格式进行处理,获取表数据,更新DataGrid控件内容

            if (keyData == (Keys.V | Keys.Control)&&this.dataGridView1.SelectedCells.Count > 0&& !this.dataGridView1.SelectedCells[0].IsInEditMode)
            {
                IDataObject idataObject = Clipboard.GetDataObject();
                string[] s = idataObject.GetFormats();
                string data;
                if (!s.Any(f => f == "OEMText"))
                {
                    if (!s.Any(f => f == "HTML Format"))
                    {
                    }
                    else
                    {
                        //data = idataObject.GetData("HTML Format").ToString();//多个单元格
                        data = idataObject.GetData("System.String").ToString();//多个单元格
                        copyClipboardTexttoGrid(data);
                        //msg = Message.;
                        msg = new Message();
                        
                        return base.ProcessCmdKey(ref msg, Keys.Control);
                    }
                }
                else
                {
                    data = idataObject.GetData("OEMText").ToString();//单个单元格,处于未编辑状态
                    int rowStart = this.dataGridView1.SelectedCells[0].RowIndex;
                    int columnStart = this.dataGridView1.SelectedCells[0].ColumnIndex;
                    this.dataGridView1.Rows[rowStart].Cells[columnStart].Value = data;
                    return base.ProcessCmdKey(ref msg, Keys.Control);
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

新增复制文本方法copyClipboardTexttoGrid ,核心思想是识别出\r\n纵向分割表格标识, \t为横向分割表格标识,然后将分割好的字符串写入DateGridView

private void copyClipboardTexttoGrid(string data)
        {
            string[] rows = data.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            string[] cols;
            int rowStart = 0,columnStart=0,i = 0,j = 0;
            if (this.dataGridView1.SelectedCells.Count > 0)
            {
                rowStart = this.dataGridView1.SelectedCells[0].RowIndex;
                columnStart = this.dataGridView1.SelectedCells[0].ColumnIndex;
            }
            int count = rowStart + rows.Length - this.dataGridView1.RowCount;
            if (count >= 0)
            {
                this.dataGridView1.Rows.Add(count + 1);
            }
            for (i = 0; i < rows.Length && i + rowStart < this.dataGridView1.RowCount; i++)
            {
                cols = rows[i].Split(new string[] { "\t" }, StringSplitOptions.None);
                for (j = 0; j < cols.Length&& j + columnStart < this.dataGridView1.ColumnCount; j++)
                {
                    this.dataGridView1.Rows[i + rowStart].Cells[j + columnStart].Value = cols[j];
                }
            }
            this.dataGridView1.ClearSelection();
            
            this.dataGridView1.Rows[i + rowStart - 1].Cells[ j + columnStart - 1].Selected = true;
        }

 

  • 13
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
### 回答1: 以下是 VB.NET 实现 DataGridView 内多个单元格复制粘贴的代码: ' 复制选定单元格 Private Sub CopySelectedCells() ' 获取选定单元格的数量 Dim cellCount As Integer = DataGridView1.GetCellCount(DataGridViewElementStates.Selected) ' 如果选定单元格数量为 ,则退出 If cellCount = Then Return End If ' 创建一个 StringBuilder 对象,用于保存复制的内容 Dim sb As New StringBuilder() ' 遍历选定单元格 For i As Integer = To cellCount - 1 ' 获取当前单元格的值 Dim cellValue As Object = DataGridView1.SelectedCells(i).Value ' 如果单元格的值为空,则跳过 If cellValue Is Nothing OrElse cellValue Is DBNull.Value Then Continue For End If ' 将单元格的值添加到 StringBuilder 对象中 sb.Append(cellValue.ToString()) ' 如果不是最后一个单元格,则添加制表符 If i < cellCount - 1 Then sb.Append(vbTab) End If Next ' 将 StringBuilder 对象中的内容复制剪贴板 Clipboard.SetText(sb.ToString()) End Sub ' 粘贴到选定单元格 Private Sub PasteToSelectedCells() ' 获取剪贴板中的文本 Dim text As String = Clipboard.GetText() ' 如果剪贴板中的文本为空,则退出 If String.IsNullOrEmpty(text) Then Return End If ' 将文本按制表符分割成数组 Dim values As String() = text.Split(vbTab) ' 获取选定单元格的数量 Dim cellCount As Integer = DataGridView1.GetCellCount(DataGridViewElementStates.Selected) ' 如果选定单元格数量为 ,则退出 If cellCount = Then Return End If ' 定义一个计数器,用于记录已经粘贴单元格数量 Dim pasteCount As Integer = ' 遍历选定单元格 For i As Integer = To cellCount - 1 ' 获取当前单元格 Dim cell As DataGridViewCell = DataGridView1.SelectedCells(i) ' 如果当前单元格不可编辑,则跳过 If Not cell.ReadOnly Then ' 如果已经粘贴完所有的单元格,则退出 If pasteCount >= values.Length Then Exit For End If ' 将文本赋值给当前单元格 cell.Value = values(pasteCount) ' 增加计数器 pasteCount += 1 End If Next End Sub 请注意,以上代码仅供参考,具体实现可能需要根据实际情况进行调整。 ### 回答2: 在VB.NET中实现DataGridView内多个单元格复制粘贴,我们可以借助Clipboard对象来实现。 首先,我们需要为DataGridView控件添加两个菜单项,一个是复制菜单项,一个是粘贴菜单项。可以通过右键点击DataGridView控件,在设计器中选择"Edit Columns",然后在弹出的编辑列窗口中添加两个菜单项。 然后,在DataGridView的CellMouseDown事件中,判断鼠标右键点击事件,并且选中了某一行,将选中行的单元格内容复制剪贴板中。代码如下: ```vb Private Sub DataGridView1_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown If e.Button = MouseButtons.Right AndAlso e.RowIndex > -1 Then DataGridView1.Rows(e.RowIndex).Selected = True Clipboard.SetText(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString()) End If End Sub ``` 在DataGridView中添加一个粘贴按钮的点击事件,在事件中将剪贴板中的内容粘贴到选中单元格中。代码如下: ```vb Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PasteToolStripMenuItem.Click Dim rowIndex As Integer = DataGridView1.SelectedCells(0).RowIndex Dim columnIndex As Integer = DataGridView1.SelectedCells(0).ColumnIndex Dim pasteData As String = Clipboard.GetText() Dim rows As String() = pasteData.Split(vbCrLf.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) For i As Integer = 0 To rows.Length - 1 Dim rowData As String() = rows(i).Split(vbTab.ToCharArray()) For j As Integer = 0 To rowData.Length - 1 If rowIndex < DataGridView1.Rows.Count AndAlso columnIndex < DataGridView1.Columns.Count Then DataGridView1.Rows(rowIndex).Cells(columnIndex).Value = rowData(j) End If columnIndex += 1 Next rowIndex += 1 Next End Sub ``` 这样,我们就实现了在DataGridView中多个单元格复制粘贴功能。 ### 回答3: 在VB.NET中,可以通过以下代码实现DataGridView内多个单元格复制粘贴功能: 首先,我们需要为DataGridView控件添加键盘快捷键的事件处理程序,以便捕获Ctrl+C(复制)和Ctrl+V(粘贴)的按键事件。在窗体的Load事件中,添加以下代码: Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load AddHandler DataGridView1.KeyDown, AddressOf DataGridView1_KeyDown End Sub 然后,在DataGridView的KeyDown事件处理程序中,我们可以根据Ctrl键的状态来执行相应的复制粘贴操作。添加以下代码: Private Sub DataGridView1_KeyDown(sender As Object, e As KeyEventArgs) If e.Control AndAlso e.KeyCode = Keys.C Then CopyCells() ElseIf e.Control AndAlso e.KeyCode = Keys.V Then PasteCells() End If End Sub 接下来,我们需要实现复制粘贴操作的具体代码。首先是复制操作CopyCells(): Private Sub CopyCells() Dim selectedCells As DataGridViewSelectedCellCollection = DataGridView1.SelectedCells Dim data As New StringBuilder() For Each cell As DataGridViewCell In selectedCells If cell.Value IsNot Nothing Then data.Append(cell.Value.ToString()) End If If cell.ColumnIndex <> DataGridView1.Columns.Count - 1 Then data.Append(vbTab) End If Next Clipboard.SetText(data.ToString()) End Sub 代码中,我们使用了一个StringBuilder对象来存储复制数据,并使用一个制表符(vbTab)分隔不同的单元格值。最后,通过Clipboard.SetText()方法将复制数据设置到剪贴板中。 然后是粘贴操作PasteCells(): Private Sub PasteCells() Dim selectedCells As DataGridViewSelectedCellCollection = DataGridView1.SelectedCells Dim cellValues() As String = Clipboard.GetText().Split(vbTab) For Each cell As DataGridViewCell In selectedCells If cellValues.Length > 0 Then cell.Value = cellValues(0) cellValues = cellValues.Skip(1).ToArray() End If Next End Sub 在粘贴操作中,我们首先将剪贴板中的文本数据按制表符分隔成一个字符串数组,然后将每个单元格的值依次设置为数组中的值。 现在,当用户按下Ctrl+C键时,选中的单元格值会被复制剪贴板中,而当用户按下Ctrl+V键时,剪贴板中的数据会被粘贴到选中的单元格中。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值