Paste from DataGridview into Excel

john noble 201 Reputation points
2021-06-09T12:39:13.293+00:00

Hi folks,

I have a datagridView in my WInforms App. It can contain thousands of rows.

I am looking for a quick way of copying the cells from the datagridView into an Excel Worksheet. When I try and do it cell by cell programmatically, it takes forever. But when I copy the cells from the datagridview using the Ctrl=C and just paste (Ctrl+V) into the worksheet it just takes a sec.

Is there a way I can simulate the above using code?

ie

When I press a form button, I want to

  1. Select all the rows in the grid (should be easy enough),
  2. Simulate a Ctrl+C keypress.
  3. Open up a Excel Worksheet (using the Microsoft.Office.Interop.Excel.Application),
  4. Select a target cell and simulate Ctrl+V

Thanks,

John

Developer technologies | Windows Forms
{count} votes

Accepted answer
  1. john noble 201 Reputation points
    2021-06-10T11:14:45.42+00:00

    Hi again,

    I managed to get a solution....

    // Select All Rows in grid
    grid.SelectAll();

    // Get the selected rows from the grid
    var contents = grid.GetClipboardContent();

    // Copy selected rows into clipboard
    Clipboard.SetDataObject(contents);

    // Set starting cell on Excel worksheet
    Microsoft.Office.Interop.Excel.Range targetRange = sh.Cells[2, 1];

    // Paste into target cell
    sh.Paste(targetRange);


1 additional answer

Sort by: Most helpful
  1. Michael Taylor 60,326 Reputation points
    2021-06-09T14:06:15.087+00:00

    Select all the data, get the clipboard content and then set the clipboard.

    grid.SelectAll();
    var contents = grid.GetClipboardContent();
    Clipboard.SetDataObject(contents);
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.