将 excel 数据粘贴到空白 DataGridView - 索引超出范围异常 [英] Pasting excel data into a blank DataGridView - Index out of range exception

查看:20
本文介绍了将 excel 数据粘贴到空白 DataGridView - 索引超出范围异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下内容的 Excel 表:

I have an excel sheet with the following:

所以,我想要实现的是从 Excel 中复制它并将其粘贴到一个空白的 DataGridView 视图中.

So, what I am trying to achieve is copy this from Excel and paste it into a blank DataGridView view.

这是我目前的代码:

private void PasteClipboard(DataGridView myDataGridView)
{
    DataObject o = (DataObject)Clipboard.GetDataObject();
    if (o.GetDataPresent(DataFormats.Text))
    {
        string[] pastedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("
".ToCharArray()), "
");
        foreach (string pastedRow in pastedRows)
        {
            string[] pastedRowCells = pastedRow.Split(new char[] { '	' });
            using (DataGridViewRow myDataGridViewRow = new DataGridViewRow())
            {
                for (int i = 0; i < pastedRowCells.Length; i++)
                    myDataGridViewRow.Cells[i].Value = pastedRowCells[i];

                myDataGridView.Rows.Add(myDataGridViewRow);
            }
        }
    }
}

当代码运行时,我收到以下错误:

When the code runs, I am getting the following error:

我是否错误地处理了手头的这项任务?

Am I approaching this task at hand incorrectly?

推荐答案

经过一番摸索,发现要先加列,再加新行,获取新创建的行的行索引,然后设置单元格值.

After some digging around, I found that I have to add columns first, then add a new row, get the row index of the newly created row, and then set the cell values.

这是更新后的代码:

DataObject o = (DataObject)Clipboard.GetDataObject();
if (o.GetDataPresent(DataFormats.Text))
{
    if (myDataGridView.RowCount > 0)
        myDataGridView.Rows.Clear();

    if (myDataGridView.ColumnCount > 0)
        myDataGridView.Columns.Clear();

    bool columnsAdded = false;
    string[] pastedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("
".ToCharArray()), "
");
    foreach (string pastedRow in pastedRows)
    {
        string[] pastedRowCells = pastedRow.Split(new char[] { '	' });

        if (!columnsAdded)
        {
            for (int i = 0; i < pastedRowCells.Length; i++)
                myDataGridView.Columns.Add("col" + i, pastedRowCells[i]);

            columnsAdded = true;
            continue;
        }

        myDataGridView.Rows.Add();
        int myRowIndex = myDataGridView.Rows.Count - 1;

        using (DataGridViewRow myDataGridViewRow = myDataGridView.Rows[myRowIndex])
        {
            for (int i = 0; i < pastedRowCells.Length; i++)
                myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
        }
    }
}

}

在这里它起作用了:

很高兴接受批评和改进这一点的有用提示.这段代码很慢...

Happy to accept criticisms and useful tips on improving this. This code is quite slow...

这篇关于将 excel 数据粘贴到空白 DataGridView - 索引超出范围异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆