簡體   English   中英

如何將Excel中的多行粘貼到C#中的DataGridView?

[英]How can I paste multi-rows from Excel to a DataGridView in C#?

我試圖將Excel表格中的行粘貼到C#中的DataGridView 我使用了以下代碼:

private void PasteClipboard(DataGridView myDataGridView)
    {
        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("\r\n".ToCharArray()), "\r\n");
            foreach (string pastedRow in pastedRows)
            {
                string[] pastedRowCells = pastedRow.Split(new char[] { '\t' });

                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];
                }
            }

在此輸入圖像描述

但是,因此,只有一行包含數據而其他行為空。 例如,如果我復制並粘貼3行,則第3行是唯一包含數據的行,而其他兩行是空的。 我究竟做錯了什么?

你需要這樣做:

int myRowIndex = myDataGridView.Rows.Add();

而不是這個:

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

請注意,在創建新行時,還會收到該行的索引,作為myDataGridView.Rows.Add();的返回值myDataGridView.Rows.Add(); 您的代碼忽略該值,而是假設新創建的行始終是最后一行: myDataGridView.Rows.Count - 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM