简体   繁体   中英

Pasting Data from Excel to DataGridView

I am trying to paste data from excel to my data grid view using C#. I found some code online which works, however the header of my data grid view is being populated with the first row of the pasted data(as per the below screenshot).

I would like to have the column headers empty and write the data in the data grid view rows if possible. Thanks in advance, please find below the code being used and screenshots.

private void btnPaste_Click(object sender, EventArgs e)
    {
        DataObject o = (DataObject)Clipboard.GetDataObject();
        if (o.GetDataPresent(DataFormats.Text))
        {
            if (dgvAuthG.RowCount > 0)
                dgvAuthG.Rows.Clear();

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

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

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

                    columnsAdded = true;
                    continue;
                }

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

                using (DataGridViewRow myDataGridViewRow = dgvAuthG.Rows[j])
                {
                    for (int i = 0; i < pastedRowCells.Length; i++)
                        myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
                }
                j++;
            }
        }
        dgvAuthG.Columns.RemoveAt(0);
        btnFormat.Enabled = true;
        btnFormatWay4.Enabled = true;
    }

enter image description here

Your code is adding the data to the column header with the line…

dgvAuthG.Columns.Add("col" + i, pastedRowCells[i]);

… the second parameter is the header text. I am not sure what you are expecting here. If you want the column header “empty” then don't add the text as the code Is doing.

I highly recommend you separate adding the columns to the grid from the loop that adds the rows. This just makes the loop code while adding row's complex and unnecessary. You “know” you will ONLY run that code (adding the columns) ONCE. Therefore, I recommend you add the columns before you start adding the rows.

The problem is that we have to read one of the rows to get the number of columns. Therefore, it would appear useful if we had that column number before we started adding rows, we could then also use it to loop through the cells in each row. You only need to do this once and it may look like below.

int totCols = pastedRows[0].Split(new char[] { '\t' }).Length;

Now that you have the number of columns for the grid, a simple loop to add the columns should work.

for (int i = 0; i < totCols; i++) {
  dgvAuthG.Columns.Add("col" + i, "col" + i);
}

This takes care of adding the columns to the grid, and will certainly make looping through the rows easier and less complex.

Before that however, I am guessing that you may want to reconsider “checking” if the grid has any existing columns or rows. It would be highly likely that the existing number of columns will NOT match what is in the “ClipBoard.” Because of this, it makes no sense to check… simply remove all the columns and start over. Otherwise a crash is almost guaranteed.

Lastly, I used a different approach to adding the rows. Basically, the code gets the index to the new row and adds the values by looping though the cells. Putting all this together may look something like below.

private void button1_Click(object sender, EventArgs e) {
  DataObject o = (DataObject)Clipboard.GetDataObject();
  if (o.GetDataPresent(DataFormats.Text)) {
    dgvAuthG.Columns.Clear();
    string[] pastedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");
    int totCols = pastedRows[0].Split(new char[] { '\t' }).Length;
    for (int i = 0; i < totCols; i++) {
      dgvAuthG.Columns.Add("col" + i, "col" + i);
    }
    string[] pastedRowCells;
    int newRowIndex;
    foreach (string pastedRow in pastedRows) {
      pastedRowCells = pastedRow.Split(new char[] { '\t' });
      newRowIndex = dgvAuthG.Rows.Add();
      for (int i = 0; i < totCols; i++) {
        dgvAuthG.Rows[newRowIndex].Cells[i].Value = pastedRowCells[i];
      }
    }
  }
  //dgvAuthG.Columns.RemoveAt(0);
  //btnFormat.Enabled = true;
  //btnFormatWay4.Enabled = true;
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM