7

我正在开发一个 C# 应用程序,其中包含很多空的 DataGridViews。用户必须用 excel 中的复制/粘贴数据填充它们。我要做的是:

int i = 0;
string s = Clipboard.GetText();

// Separate lines
string[] lines = Regex.Split(s, "\r\n");
foreach (string line in lines)
{
    // Separate each cell
    string[] cells = line.Split('\t');
    foreach (string cell in cells)
    {
        // If we selected as many cells as copied
        if (dataGridView.SelectedCells.Count == (lines.Length-1)*(cells.Length))
        {
            dataGridView.SelectedCells[i].Value = cell;
            i++;
        }
    }
}

问题是,如果我复制这样的内容(在 excel 上):

1   2   3
4   5   6

我的数据网格视图将如下所示:

6   4   2
5   3   1

我真的不知道该怎么做才能解决这个问题...在此先感谢

4

2 回答 2

2
  1. 将剪贴板数据转换为二维数组。记住每个维度的长度。
  2. 遍历选定的单元格并找到左上角和右下角的单元格。从中您可以确定它的尺寸是否合适。
  3. 使用双循环,将剪贴板数据从数组位置直接映射到单元格坐标(不使用选定的单元格),使用左上角单元格坐标作为偏移量。

或者,您可以创建一个包含属性 Row、Col 和 Value 的小类/结构的列表,而不是二维数组。然后只需迭代它而不是双循环。

于 2012-04-11T22:08:09.520 回答
1

代替

dataGridView.SelectedCells[i].Value = cell;

dataGridView.SelectedCells[(dataGridView.SelectedCells.Count-1) - i].Value = cell;

于 2012-04-11T17:39:32.153 回答