當我們載入 Excel 檔案到 Windows 表單應用程式時,最常見的方法是使用 Streams 去讀/寫 檔案。另一種更好的方法是直接拖拽 Excel 檔案到
FlexGrid 上。
這個例子使用 Drag 和 Drop 特性來實現該應用。下面我們分部闡述如何?:
1.建立使用者自訂控制項
在使用者自訂控制項中添加 ComponentOne C1FlexGrid,我們使用 ComponentOne C1Command's MainMenu 和 ComponentOne 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"); } }
4.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 下載
很高興能和大家分享 ComponentOne 的使用方法、討論 ComponentOne 使用過程中遇到的問題。
葡萄城控制項產品網站:http://www.gcpowertools.com.cn/
葡萄城支援人員論壇:http://gcdn.grapecity.com/