有什么办法可以使datagridview控件,以便用户可以使用Ctrl+C
和Ctrl+V
从Excel复制和粘贴多个单元格?
If you get simple Excel content by calling Clipboard.GetText()
it will return a string.
In it the rows will be separated by Linefeeds
(\\r\\n) and the fields by Tabs
(\\t).
Look at the code below, this will give you something to work with..:
// Before you press the button copy some excel cells!
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
dataGridView1.Columns.Add("one", "one");
dataGridView1.Columns.Add("two", "two");
dataGridView1.Columns.Add("three", "three");
dataGridView1.Columns.Add("four", "four");
dataGridView1.Columns.Add("five", "five");
dataGridView1.Rows.Add(5);
dataGridView1.Focus();
dataGridView1.CurrentCell = dataGridView1[1, 1];
string s = Clipboard.GetText();
string[] lines = s.Replace("\n", "").Split('\r');
string[] fields;
int row = 0;
int column = 0;
foreach (string l in lines)
{
fields = l.Split('\t');
foreach (string f in fields)
dataGridView1[column++, row].Value = f;
row++;
column = 0;
}
}
Pasting with Control-V is trickier, start with a button!
It would involve capturing the Control-V and processing it; this can be a bit hard to debug, though..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.