拖拽 Excel 到 C1FlexGrid
当我们加载 Excel 文件到 Windows 窗体应用程序时,最常见的方法是使用 Streams 去读/写 文件。另一种更好的方法是直接拖拽 Excel 文件到
FlexGrid 上。
这个例子使用 Drag 和 Drop 特性来实现该应用。下面我们分部阐述如何实现:
1.创建用户自定义控件
在用户自定义控件中添加 C1FlexGrid,我们使用 C1Command's MainMenu 和 DockingTab 控件去模拟 Excel 菜单和 Sheets
Tab。使用 Label 和 TextBox 去展示当前选中索引和内容。
UI 布局如截图:
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");
- }
- }
复制代码 LoadExcelInFiel 方法使用两个方法:AddTabs() 和 UpdateFields() 。这两个方法的作用是创建类似于 Excel 的 SpreadSheet 界面。- private void AddTabs()
- {
- _sheetTabs.TabPages.Clear();
- string[] sheetnames = _flex.LoadExcelSheetNames(file);
- foreach (string str in sheetnames)
- {
- C1DockingTabPage dtpage = new C1DockingTabPage();
- dtpage.Name = str;
- dtpage.Text = str;
- _sheetTabs.TabPages.Add(dtpage);
- }
- _sheetTabs.SelectedIndex = 0;
- }
- //Method to update the fields in the UI
- private void UpdateFields()
- {
- SetRowColNames();
- int selcol = _flex.Col;
- int selrow = _flex.Row;
- label1.Text = _flex.GetDataDisplay(0, selcol) + selrow.ToString();
- try { textBox1.Text = _flex.GetDataDisplay(selrow, selcol); }
- catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message);}
-
- }
复制代码
更多请参考 Demo
|