Is it possible to paste Excel / CSV data from clipboard to DataGridView in C#?
I use DataGridView control to manage a simple dictionary (several columns and a few hundred rows). DataGridView functionality is almost sufficient. I can add new rows, modify values and copy data from it to Exce开发者_StackOverflowl. One thing I cannot do is to copy data from Excel to my control. Is it possible with some properties? Or is some code required to do this?
this has been edited from the codeprojet writeup. Slightly different `
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;
}
}
Yes you can!
Take a look at some of the code here and see if that helps.
You can read the excel sheet to a dataset then bind the dataset to the grid. I think you should be able to make your amendments then write out to excel again when finished editing.
Also this MSDN link: how to PASTE (Ctrl+V, Shift+Ins) the data from clipboard to DataGridView
With code for .NET C#, VB and C++
(In the GetData method you probably want to specify Format.UnicodeText)
精彩评论