[英]Is it possible to paste Excel / CSV data from clipboard to DataGridView in C#?
我使用DataGridView控件来管理一个简单的字典(几列和几百行)。 DataGridView功能几乎足够。 我可以添加新行,修改值并将数据从其中复制到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工作表读取到数据集,然后将数据集绑定到网格。 我认为您应该能够进行修改,然后在完成编辑后再次写出Excel。
也是这个MSDN链接: 如何将数据从剪贴板粘贴(Ctrl + V,Shift + Ins)到DataGridView
使用.NET C#,VB和C ++的代码
(在GetData方法中,您可能要指定Format.UnicodeText)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.