是否可以将剪贴板中的Excel / CSV数据粘贴到C#中的DataGridView?

时间:2009-11-05 10:56:00

标签: c# .net excel datagridview csv

我使用DataGridView控件来管理一个简单的字典(几列和几百行)。 DataGridView功能几乎已足够。我可以添加新行,修改值并将数据从中复制到Excel。我不能做的一件事是将数据从Excel复制到我的控件。有些属性可能吗?或者是否需要一些代码来执行此操作?

4 个答案:

答案 0 :(得分:3)

这是从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;
            }
        }

答案 1 :(得分:2)

是的,你可以!

查看一些代码here,看看是否有帮助。

答案 2 :(得分:0)

您可以将Excel工作表读取到数据集,然后将数据集绑定到网格。我认为您应该能够进行修改,然后在完成编辑后再次写出excel。

答案 3 :(得分:0)

此MSDN链接:how to PASTE (Ctrl+V, Shift+Ins) the data from clipboard to DataGridView

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

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

相关问题