2017/02/22

C#.Net 將DataGridView內的資料複製到剪貼簿

執行結果:


複製到記事本

複製到Excel




Code:
using System.Windows.Forms;

namespace CYFang
{
    public partial class Form1 : Form
    {

        public class Info
        {
            public string name { get; set; }
            public int age { get; set; }
        }

        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            InitUI();
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitUI()
        {
            DataGridView dgv = new DataGridView
            {
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                AutoGenerateColumns = true,
                //設定複製模式
                ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
            };

            var infos = new[] {
                new Info { name = "王小名", age = 18 },
                new Info { name = "陳小白", age = 20 },
                new Info { name = "", age = 20 }
            };

            dgv.DataBindingComplete += (s, e) =>
            {
                dgv.Columns["name"].HeaderText = "姓名";
                dgv.Columns["age"].HeaderText = "年紀";
            };

            dgv.DataSource = infos;

            var button = new Button
            {
                Text = "Copy",
                Location = new System.Drawing.Point(0, 150)
            };

            button.MouseClick += (s, e) =>
            {
                //選取所有行
                dgv.SelectAll();
                //複製到剪貼簿
                Clipboard.SetDataObject(dgv.GetClipboardContent());
                //設定複製格式
                //Clipboard.SetDataObject(dgv.GetClipboardContent().GetData(DataFormats.UnicodeText));
                //取消選取
                dgv.ClearSelection();
                MessageBox.Show("複製完成");
            };

            this.Controls.Add(dgv);
            this.Controls.Add(button);
        }
            
    }
}