C# routine to paste Excel table data into a DataGridView

(c) 2013 by Barton Paul Levenson


Language:
C#

Dialect:
Microsoft Visual C# Express 2010

Discussion:
This routine assumes you've copied a rectangular array of cells from Excel into the Windows Clipboard. It pastes that data into a Microsoft DataGridView control in a C# GUI program. :)


        // PasteInData pastes clipboard data into the grid passed to it.
        static void PasteInData(ref DataGridView dgv)
        {
            char[] rowSplitter = {'\n', '\r'};  // Cr and Lf.
            char columnSplitter = '\t';         // Tab.

            IDataObject dataInClipboard = Clipboard.GetDataObject();

            string stringInClipboard = 
                dataInClipboard.GetData(DataFormats.Text).ToString();

            string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, 
                StringSplitOptions.RemoveEmptyEntries);

            int r = dgv.SelectedCells[0].RowIndex;
            int c = dgv.SelectedCells[0].ColumnIndex;

            if (dgv.Rows.Count < (r + rowsInClipboard.Length))
                dgv.Rows.Add(r + rowsInClipboard.Length - dgv.Rows.Count);

            // Loop through lines:

            int iRow = 0;
            while (iRow < rowsInClipboard.Length)
            {
                // Split up rows to get individual cells:

                string[] valuesInRow = 
                    rowsInClipboard[iRow].Split(columnSplitter);

                // Cycle through cells.
                // Assign cell value only if within columns of grid:

                int jCol = 0;
                while (jCol < valuesInRow.Length)
                {
                    if ((dgv.ColumnCount - 1) >= (c + jCol))
                        dgv.Rows[r + iRow].Cells[c + jCol].Value = 
                        valuesInRow[jCol];

                    jCol += 1;
                } // end while

                iRow += 1;
            } // end while
        } // PasteInData


Page created:07/08/2013
Last modified:  07/08/2013
Author:BPL