【问题标题】:Winform Drag Drop into excelWinform拖放到excel
【发布时间】:2015-07-31 12:50:15
【问题描述】:

我想从我的 winform 拖放到 Excel 中。例如,在 Winform 中按住一个按钮(或 DataGridView 中的一行)并将其拖放到 Excel 单元格中会执行一些操作或将一些数据写入 Excel 单元格。

我说的是winform和Excel之间的拖放,而不是winform组件之间的拖放。

我记得曾经看过一个示例,但在 Google 上找不到了。

更新:按照 Avantol13 的回答,

我们如何提取发送到 Excel 的对象?在示例中,将字符串写入单元格,然后检查该单元格的内容以执行进一步的操作是一种 hack。也许类似于 DragDrop 事件,我们可以提取从 e.Data.GetData(e.Data.GetFormats()[0]) 发送的数据

此外,使用Application_SheetChange 知道drop 事件将导致它循环为Application_SheetChange -> 修改单元格的代码,如示例中(删除单元格并编写新内容)-> 再次触发@987654324 @等

提前致谢。

【问题讨论】:

  • This 可能就是您想要的。有点过时了,但可能仍适用于您的情况
  • 感谢 Avantol13。这就是我要找的。一个问题:我们如何提取发送到 Excel 的对象?在示例中,将字符串写入单元格,然后检查该单元格的内容以执行进一步的操作是一种 hack。也许类似于 DragDrop 事件,我们可以提取从 e.Data.GetData(e.Data.GetFormats()[0]) 发送的数据
  • 我会用你刚才描述的细节更新你的问题,也许对此有更了解的人可以回答。

标签: c# excel winforms datagridview drag-and-drop


【解决方案1】:

Sean Sexton provides an excellent example 了解如何将数据从 WPF 窗口拖放到 Excel。我已经修改了他的示例,以便它可以与 WinForms 一起使用。 试试这个:

private void control_MouseDown(object sender, MouseEventArgs e)
{
    List<string> stringItems = new List<string>() { "Value1", "Value2", "Value3" };

    //Separate all values with tabs
    string someValues = string.Join("\t", stringItems);

    DataObject data = new DataObject(DataFormats.Text, someValues);
    DoDragDrop(data, DragDropEffects.Copy);
}

【讨论】:

  • 这仍将仅发送文本作为拖动对象。它被写入连续单元格的事实是因为文本是逗号分隔的。但是,我认为我们不能说例如“写在列中”
【解决方案2】:

根据 Avantol13 的建议,我想出了一个办法。

当 Excel 的工作表被修改时挂钩 Excel_Drop 事件

Application.SheetChange += new AppEvents_SheetChangeEventHandler(Excel_Drop);

对于开始拖动的按钮:

private void _Button1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DragDropEffects dde1 = DoDragDrop("Action1", DragDropEffects.All);
            }
        }

另一个按钮将发送“Action2”作为标志。

private void Excel_Drop(object dropObj, Range target)
    {
        String dragData = Convert.ToString(target.Value2);

        if (dragData.Equals("Action1"))
        {
            Application.SheetChange -= Excel_Drop;
            DoAction1();
            Application.SheetChange += Excel_Drop;
            return;
        }
        if (dragData.Equals("Action2"))
        {
            Application.SheetChange -= Excel_Drop;
            DoAction2();
            Application.SheetChange += Excel_Drop;
            return;
        }
    }

为了解决循环问题:丢弃事件触发Excel_drop->调用DoActionx()再次修改工作表->依次重新触发Excel_drop,我阻止了该事件。

然而,基于这种使用文本标志的方法仍有几个缺点:

  1. 当在 winform 组件之间拖放时,除了文本作为拖动对象(如 here)外,我无法发送任何内容。因此,无论如何我都需要发送文本标志,删除它并执行我的操作。除了作为黑客之外,我无法验证“仅当单元格为空时才执行操作”,因为无论如何丢弃都会用标志覆盖我的单元格。 欢迎任何建议。

  2. 我们如何发送任何东西作为拖动对象?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多