是否有可能从剪贴板粘贴Excel / CSV数据到C#中的DataGridView?

我使用DataGridView控件来pipe理一个简单的字典(几列和几百行)。 DataGridViewfunction已经足够了。 我可以添加新的行,修改值并将其中的数据复制到Excel。 我不能做的一件事是从Excel复制数据到我的控制。 有些物业可能吗? 还是需要一些代码来做到这一点?

是的你可以!

看看这里的一些代码,看看是否有帮助。

这是从codeprojet书面编辑。 略有不同 `

private void PasteClipboard() { try { string s = Clipboard.GetText(); string[] lines = s.Split('\n'); int iFail = 0, iRow = dgData.CurrentCell.RowIndex; int iCol = dgData.CurrentCell.ColumnIndex; DataGridViewCell oCell; if (dgData.Rows.Count < lines.Length) dgData.Rows.Add(lines.Length-1); foreach (string line in lines) { if (iRow < dgData.RowCount && line.Length > 0) { string[] sCells = line.Split('\t'); for (int i = 0; i < sCells.GetLength(0); ++i) { if (iCol + i < this.dgData.ColumnCount) { oCell = dgData[iCol + i, iRow]; if (!oCell.ReadOnly) { if (oCell.Value==null|| oCell.Value.ToString() != sCells[i]) { oCell.Value = Convert.ChangeType(sCells[i], oCell.ValueType); // oCell.Style.BackColor = Color.Tomato; } else iFail++; //only traps a fail if the data has changed //and you are pasting into a read only cell } } else { break; } } iRow++; } else { break; } if (iFail > 0) MessageBox.Show(string.Format("{0} updates failed due" + " to read only column setting", iFail)); } } catch (FormatException) { MessageBox.Show("The data you pasted is in the wrong format for the cell"); return; } } 

您可以读取Excel表格到数据集,然后将数据集绑定到网格。 我认为你应该能够做出修改,然后在完成编辑时再次写出优秀的。

也是这个MSDN链接: 如何粘贴(Ctrl + V,Shift + Ins)剪贴板中的数据到DataGridView

用.NET C#,VB和C ++的代码

(在GetData方法中,您可能需要指定Format.UnicodeText)