C# excel’den dataGridView kopyalama
30 Haziran 2016 / 12:41
Burak
Merhaba arkadaşlar kimi zaman lazım olabiliyor. Excel’de seçtiğimiz bir değerleri dataGridView kopyalamamız gerekiyor.Bunun için aşağıdaki kodu herhangi bir event’a yazarak kullanabilirsiniz.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
try { DataGridViewRow selectedRow; /* Find first selected cell's row (or first selected row). */ if (dataGridView1.SelectedRows.Count > 0) selectedRow = dataGridView1.SelectedRows[0]; else if (dataGridView1.SelectedCells.Count > 0) selectedRow = dataGridView1.SelectedCells[0].OwningRow; else return; /* Get clipboard Text */ string clipText = Clipboard.GetText(); /* Get Rows ( newline delimited ) */ string[] rowLines = Regex.Split(clipText, "\r\n"); foreach (string row in rowLines) { /* Get Cell contents ( tab delimited ) */ string[] cells = Regex.Split(row, "\t"); DataGridViewRow r = new DataGridViewRow(); foreach (string sc in cells) { DataGridViewTextBoxCell c = new DataGridViewTextBoxCell(); c.Value = sc; r.Cells.Add(c); } dataGridView1.Rows.Insert(selectedRow.Index, r); } } catch (System.ArgumentException ex) { } catch (Exception ex) { MessageBox.Show(ex.Message); } |
Alternatif kod olarak ise aşağıdaki kodu kullanabilirsiniz
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
if(e.KeyCode==Keys.Control || e.KeyCode==Keys.V) { DataObject o = (DataObject)Clipboard.GetDataObject(); if (o.GetDataPresent(DataFormats.Text)) { int rowOfInterest = dataGridView1.CurrentCell.RowIndex; string[] selectedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n"); if (selectedRows == null || selectedRows.Length == 0) return; foreach (string row in selectedRows) { if (rowOfInterest >= dataGridView1.Rows.Count) break; try { string[] data = Regex.Split(row, "\t"); int col = dataGridView1.CurrentCell.ColumnIndex; foreach (string ob in data) { if (col >= dataGridView1.Columns.Count) break; if (ob != null) dataGridView1[col, rowOfInterest].Value = Convert.ChangeType(ob, dataGridView1[col, rowOfInterest].ValueType); col++; } } catch (Exception enterException) { //do something here } rowOfInterest++; } } } |
Etiketler: c# excel dataGridView copy / paste
Bu Yazılarıda Okuyabilirsiniz...
Bir cevap yazın