Date: 02.11.2018 5:23:50
Excel помещает данные в буфер обмена в нескольких форматах. Проще всего, наверное, прочитать HTML:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //Добавить ссылку: COM / Microsoft HTML Objects Library private void button1_Click(object sender, EventArgs e) { var data = Clipboard.GetDataObject(); string html = (string)data.GetData("HTML Format"); if (html==null) { MessageBox.Show("В буфере обмена нет подходящих данных"); return; } mshtml.HTMLDocument doc = null; mshtml.IHTMLDocument2 d2 = null; mshtml.IHTMLDocument3 d = null; mshtml.IHTMLElementCollection tables = null; mshtml.IHTMLElement table = null; mshtml.IHTMLElementCollection rows = null; mshtml.IHTMLElementCollection cells = null; mshtml.IHTMLElement rowelem = null; mshtml.IHTMLElement cellelem = null; DataTable dt = new DataTable(); try { //грузим документ в парсер doc = new mshtml.HTMLDocument(); d2 = (mshtml.IHTMLDocument2)doc; d2.write(html); //находим table d = (mshtml.IHTMLDocument3)doc; tables = d.getElementsByTagName("table"); if (tables.length == 0) { MessageBox.Show("В буфере обмена нет таблицы"); return; } table = tables.item(0); rows = (table as mshtml.IHTMLElement2).getElementsByTagName("tr"); for (int n = 0; n < rows.length; n++) { if (rowelem != null) { Marshal.ReleaseComObject(rowelem); rowelem = null; } if (cells != null) { Marshal.ReleaseComObject(cells); cells = null; } rowelem = rows.item(n); //получаем значения ячеек List<string> values = new List<string>(); cells = (rowelem as mshtml.IHTMLElement2).getElementsByTagName("td"); for (int i=0;i< cells.length; i++) { if (cellelem != null) { Marshal.ReleaseComObject(cellelem); cellelem = null; } cellelem = cells.item(i); values.Add(cellelem.innerText); } //добавим недостающие столбцы в DataTable if (dt.Columns.Count < values.Count) { int cols = values.Count - dt.Columns.Count; for (int k = 0; k < cols; k++) { dt.Columns.Add(); } } //установим значения ячеек в DataTable DataRow row = dt.NewRow(); for(int j = 0; j < values.Count; j++) { row[j] = values[j]; } dt.Rows.Add(row); } dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = dt; } finally { //освобождение ресурсов if (doc != null) Marshal.ReleaseComObject(doc); if (d2 != null) Marshal.ReleaseComObject(d2); if (d != null) Marshal.ReleaseComObject(d); if (tables != null) Marshal.ReleaseComObject(tables); if (table != null) Marshal.ReleaseComObject(table); if (rows != null) Marshal.ReleaseComObject(rows); if (cells != null) Marshal.ReleaseComObject(cells); if (rowelem != null) Marshal.ReleaseComObject(rowelem); if (cellelem != null) Marshal.ReleaseComObject(cellelem); } } } }
Автор: VadimTagil