多语言展示
当前在线:1667今日阅读:176今日分享:34

拖拽Excel到C1 FlexGrid for WinForms

当我们加载 Excel 文件到 Windows 窗体应用程序时,最常见的方法是使用 Streams 去读/写 文件。另一种更好的方法是直接拖拽 Excel 文件到 FlexGrid 上。   这个例子使用 Drag 和 Drop 特性来实现该应用。下面我们分部阐述如何实现
工具/原料
1

ComponentOne

2

FlexGrid for WinForms

方法/步骤
1

创建用户自定义控件     在用户自定义控件中添加 C1FlexGrid,我们使用 C1Command's MainMenu 和 DockingTab 控件去模拟 Excel 菜单和 Sheets Tab。使用 Label 和 TextBox 去展示当前选中索引和内容

2

拖拽 Excel 到 C1FlexGrid      是指 C1FlexGrid.DropMode 为 Manual。添加 C1FlexGrid DragEnter 和 DragDrop 事件。在 DragEnter 事件中更改 光标形状。我们我需要创建 “file” 变量去存储添加的文件名称string file;         private void _flex_DragEnter(object sender, DragEventArgs e)         {            if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)                e.Effect = DragDropEffects.Move;            else                e.Effect = DragDropEffects.None;         }

3

现在我们需要在 DragDrop 事件中操作拖拽到 C1FlexGrid 中的 Excel 文件。Drop 事件可以捕捉到文件名和路径。这时我们可以使用 C1FlexGrid .LoadExcel 方法去加载 Excel 文件。但是我们需要去检查拖拽的文件是否为 BIFF8(.XlS) 或者 OpenXML(xlsx)文件。private void _flex_DragDrop(object sender, DragEventArgs e)        {            file = string.Empty;             string[] str = (string[])e.Data.GetData(DataFormats.FileDrop);             foreach (string s in str)                file += s;            LoadExcelInFlex();        }                private void LoadExcelInFlex()        {            if ((file.EndsWith(".xls")) || (file.EndsWith(".xlsx")))            {                _flex.DataSource = null;                _flex.LoadExcel(file);                AddTabs();                UpdateFields();            }            else            {                MessageBox.Show("Please select an Excel file");            }        }

推荐信息