Copy&Paste فایل اکسل در DataGridView

یک برنامه ویندوزی ایجاد کرده و یک دکمه و یک Datagrid بر روی آن قرار دهید :
copy-and-paste-excel-file-in-datagridview-csharp-01
بر روی دکمه دوبار کلیک و کدهای زیر را بنویسید :

using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace ExcelToDataGrid
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        private void button1_Click(object sender, EventArgs e)
        {
            PasteClipboard(dataGridView1);
        }
    }
}

حال محتوایی را که می خواهید از فایل Excel در داخل دیتاگرید کپی کنید را انتخاب و کپی کنید :
copy-and-paste-excel-file-in-datagridview-csharp-02
و سپس دکمه Paste برنامه را بزنید :
copy-and-paste-excel-file-in-datagridview-csharp-03