|
前一篇文章介紹了Excel中的菜單系統(tǒng),在創(chuàng)建完菜單和工具欄之后,就要著手進(jìn)行功能的開發(fā)了。不論您采用何種方式來開發(fā)Excel應(yīng)用程序,了解Excel對象模型尤其重要,這些對象是您與Excel進(jìn)行交互的基石。據(jù)不完全統(tǒng)計,Excel的對象模型中有270多個對象及超過5000多個屬性和方法。通過這些對象及方法,您可以充分利用Excel來定制化您的插件。 Excel的所有對象,事件,方法和屬性在這里不可能全部介紹完。本文簡要介紹一下Excel的整體文檔對象模型,以及一些比較重要的,平常開發(fā)中需要頻繁接觸到的對象,屬性,事件及方法,如Application,Range對象等,使您對Excel的整個結(jié)構(gòu)有一個簡單的了解。后面在編程中遇到問題了,您可以快速定位知道需要設(shè)置或者調(diào)用哪個對象及其方法,然后根據(jù)關(guān)鍵字到Google或者M(jìn)SDN上方便查找。本文大部分內(nèi)容參照MSDN上的這篇文章Understanding the Excel Object Model from a .NET Developer's Perspective 如果您對英文沒有問題,建議您直接去MSDN看原文。 一 Excel 對象模型簡介在與Excel進(jìn)行交互之前,了解Excel對象模型的整體結(jié)構(gòu)非常重要,這使得我們對Excel有一種更整體全面的了解。下圖是Excel的對象模型的整個層級結(jié)構(gòu)。 根據(jù)這個圖,我們打開一個Excel,可以有一種非常直觀形象的了解。 圖中可以看到,Excel對象模型基本模擬了UI界面:
更詳細(xì)地Excel的對象模型圖,如下,圖中灰色的部分存在于office.dll中所有Office應(yīng)用程序中都存在的對象。
以上是Excel文檔對象模型的大概全部的對象模型。其中最重要的幾個對象為Application,Workbook,Worksheet 和Range對象。下面就簡單介紹下這些對象中的一些屬性,方法及事件。 二 Application對象Application是根對象,代表著Excel應(yīng)用程序本身,一切Excel中的其他對象都有它直接或者間接創(chuàng)建。 您可以回想到前面我們在Shared Add-in項目中創(chuàng)建Excel菜單和工具條時接觸到的對象。我們首先是在Connect方法中保存了 application對象,然后在該對象上創(chuàng)建了MenuBar和Toolbar。Application對象有一些熟悉,事件和方法,在我們編程中經(jīng)常會用到,現(xiàn)在就稍微講一下: 2.1 Application中控制Excel狀態(tài)和顯示的方法和屬性Application中控制Excel狀態(tài)和顯示的方法和屬性有很多,表一中列出了常用的幾個屬性。有一個屬性是需要重新啟用后才可以生效的。
上面列出的屬性中,最可能用到的是ScreenUpdating屬性,正確使用該屬性能夠大幅提高應(yīng)用程序的性能。默認(rèn)的,該屬性為true,即每一次修改就會刷新整個界面,這會使得應(yīng)用程序變慢,尤其是在往單元格填充大量數(shù)據(jù)的時候。所以一般的做法是,在填充數(shù)據(jù)之前保存ScreenUpdating屬性,然后將ScreenUpdating屬性設(shè)置為false,禁止屏幕刷新,然后填充數(shù)據(jù),最后將之前保存的ScreenUpdating屬性賦值回來。下面的代碼演示了這一做法: Boolean oldScreenUpdate = this.Application.ScreenUpdating; try { this.Application.ScreenUpdating = false; //to fill in a large range that time comsuming } finally { this.Application.ScreenUpdating = oldScreenUpdate; } 2.2 Application中返回的對象從Application對象中可以獲取很多有用的對象。如ActiveCell返回當(dāng)前活動的單元格;ActiveChart,返回當(dāng)前選中的活動的圖表;ActiveSheet、ActiveWindows分別返回活動的Sheet頁和窗口;Selection屬性返回當(dāng)前選中的對象,可能是Range,Worksheet或者是一個窗體;Workbooks,Sheets,Charts返回當(dāng)前Excel中所有工作簿,工作表,圖表的集合。 通常,我們接觸最多的是Application對象的Workbooks屬性,該對象是當(dāng)前Excel打開的所有的工作簿文件。一個Workbook就是一個.xls或者.xlsx文件。下面簡單講解Workbooks對象。
// Create a new workbook object Excel.Workbook wb = this.Application.Workbooks.Add(Type.Missing);
// Close all workbooks this.Application.Workbooks.Close();
// Open an exist workbook Excel.Workbook wbOpenExistFile = this.Application.Workbooks.Open( "C:\\YourPath\\Yourworkbook.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
這些操作可以通過OpenText,OpenDatabase,OpenXml方法來實(shí)現(xiàn),方法參數(shù)可能需要您詳細(xì)指定。
有時候我們可能需要從當(dāng)前的工作簿文件中,找到指定的工作簿文件進(jìn)行操作。一般的我們可以通過Workbooks屬性通過索引器傳入index來返回,或者通過工作簿名稱來返回。需要注意的是,工作簿沒有保存前,不需要后綴,保存后需要帶上后綴來進(jìn)行訪問,代碼如下: //Get an exist workbook form current workbooks Excel.Workbook wbFind = this.Application.Workbooks[1]; // Before Book1 is saved: wbFind = this.Application.Workbooks["Book1"]; // After Book1 is saved: wbFind = this.Application.Workbooks["Book1.xls"]; 2.3 Application中的方法Application對象提供了一些方法,包括單元格的重新計算,撤銷操作等。
// Cell calculate this.Application.Calculate(); // Or... this.Application.Calculate(); // Or... this.Application.get_Range("A1", "B12").Calculate();
2.4 Application中文件操作方法
//using FileDialog to open an exist file Office.FileDialog dlg = this.Application.get_FileDialog( Office.MsoFileDialogType.msoFileDialogOpen); dlg.Filters.Clear(); dlg.Filters.Add("Excel Files", "*.xls;*.xlw", Type.Missing); dlg.Filters.Add("All Files", "*.*", Type.Missing); if (dlg.Show() != 0) dlg.Execute(); 2.5 Application中其他一些有用的對象Application中還有一些其他有用的對象,如WorksheetFunction,該對象包括了一系列靜態(tài)或者共享方法,這些方法都是對Excel內(nèi)置函數(shù)的包裝。
Excel.Worksheet ws = (Excel.Worksheet)this.Application.ActiveSheet; Excel.Range rng = ws.get_Range("RandomNumbers", Type.Missing); System.Random rnd = new System.Random(); for (int i = 1; i <= 20; i++) ws.Cells[i, 2] = rnd.Next(100); rng.Sort(rng, Excel.XlSortOrder.xlAscending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlNo, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal); Excel.WorksheetFunction wsf = this.Application.WorksheetFunction; ws.get_Range("Min", Type.Missing).Value2 = wsf.Min(rng, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Arrange the windows this.Application.Windows.Arrange( Excel.XlArrangeStyle.xlArrangeStyleTiled, Type.Missing, Type.Missing, Type.Missing);
//Add a name range Excel.Name nm = this.Application.Names.Add( "NewName", @"='Other Application Members'!$A$6", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 后面使用該名稱即可找到該名稱代表的Range對象: // Retrive a name Range this.Application.get_Range("NewName", Type.Missing).Value2 = "Hello, World!"; 2.6 Application對象中的事件Application對象除了上面講解的一些有用的方法和屬性之外,還有一些事件。這些事件大致分為Sheet行為相關(guān)的事件、Window行為相關(guān)事件Workbook管理相關(guān)的事件。下面簡要介紹這些事件的作用。 Sheet相關(guān)事件:
以上application上的事件在Workbook類上也存在。application上的事件對所有的工作簿都有效,而Workbook上的這些事件僅對該Workbook有效。 Windows行為相關(guān)事件:
Workbook行為相關(guān)事件:
三 Workbook對象Workbook對象也有很多屬性和方法,下面僅介紹一些比較常用的方法和屬性。 Workbook屬性
文檔屬性 Excel文檔允許用戶將一些信息保存到文件屬性中。Excel提供了一些列內(nèi)置的屬性,我們也可以添加自己的屬性。
Workbook類的BuiltInDocumentProperties屬性可以獲取和設(shè)置那只的屬性,CustomDocumentProperties可以獲取和設(shè)置自定義屬性。屬性以鍵值對表示,我們可以使用屬性的關(guān)鍵字或者Index來獲取屬性。下面的代碼演示了獲取所有的內(nèi)置和自定義的屬性,DumpPropertyCollection方法用來打印屬性。 //Display the document property private void DisplayDocumentProperties() { Office.DocumentProperty prp = null; Office.DocumentProperties prps = (Office.DocumentProperties) this.Application.ActiveWorkbook.BuiltinDocumentProperties; Excel.Range rng = this.Application. get_Range("DocumentProperties", Type.Missing); int i = 0; try { this.Application.ScreenUpdating = false; try { // Set the Revision Number property: prp = prps["Revision Number"]; prp.Value = Convert.ToInt32(prp.Value) + 1; // Dump contents of the collection: i = DumpPropertyCollection(prps, rng, i); } catch (Exception ex) { MessageBox.Show(ex.Message, this.Application.Name); } // Work with custom properties: try { prps = (Office.DocumentProperties) this.Application.ActiveWorkbook.CustomDocumentProperties; DumpPropertyCollection(prps, rng, i); } catch (Exception ex) { MessageBox.Show(ex.Message, this.Application.Name); } // Add a custom property: try { // Delete the property, if it exists. prp = prps["Project Name"]; prp.Delete(); } catch { // Do nothing if you get an exception. } try { // Add a new property. prp = prps.Add("Project Name", false, Office.MsoDocProperties.msoPropertyTypeString, "White Papers", Type.Missing); } catch (Exception ex) { MessageBox.Show(ex.Message, this.Application.Name); } } finally { this.Application.ScreenUpdating = true; } } private int DumpPropertyCollection( Office.DocumentProperties prps, Excel.Range rng, int i) { foreach (Office.DocumentProperty prp in prps) { rng.get_Offset(i, 0).Value2 = prp.Name; try { if (prp.Value != null) { rng.get_Offset(i, 1).Value2 = prp.Value.ToString(); } } catch { // Do nothing at all. } i += 1; } return i; } 一般地,我們可以將一些和文檔相關(guān)的信息或者臨時數(shù)據(jù)保存到自定義信息中。 文檔樣式 在Excel開發(fā)中,我們經(jīng)常要對單元格進(jìn)行格式化,這時,我們可能需要自定義一些樣式,然后給其命名,然后下次直接按照名稱賦給樣式即可。
我們可以通過Workbook的Styles屬性來對這些文檔樣式進(jìn)行添加,修改和刪除。下面代碼演示了如何創(chuàng)建或者修改一個樣式: // Apply Style private void ApplyStyle() { const String STYLE_NAME = "PropertyBorder"; // Get the range containing all the document properties. Excel.Range rng = GetDocPropRange(); Excel.Style sty; try { sty = this.Application.ActiveWorkbook.Styles[STYLE_NAME]; } catch { sty = this.Application.ActiveWorkbook.Styles.Add(STYLE_NAME, Type.Missing); } sty.Font.Name = "Verdana"; sty.Font.Size = 12; sty.Font.Color = ColorTranslator.ToOle(Color.Blue); sty.Interior.Color = ColorTranslator.ToOle(Color.LightGray); sty.Interior.Pattern = Excel.XlPattern.xlPatternSolid; rng.Style = STYLE_NAME; rng.Columns.AutoFit(); }
工作表對象 Workbook的Sheets屬性返回該工作簿包含的所有工作表對象。這些對象可以是工作表也可以是Chart對象,下面的代碼列出了當(dāng)前工作簿中的所有對象。 // Show all the workSheet name in the active workbook private void ListSheets() { int i = 0; Excel.Range rng = this.Application.get_Range("Sheets", Type.Missing); foreach (Excel.Worksheet sh in this.Application.ActiveWorkbook.Sheets) { rng.get_Offset(i, 0).Value2 = sh.Name; i = i + 1; } } WorkSheet有一些很有用的屬性和方法:
// Hide Worksheet private void HideTheSheet() { ((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[1]).Visible = Excel.XlSheetVisibility.xlSheetVeryHidden; }
Excel.Worksheet sh = this.Application.Sheets.Add( Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//Copy Worksheet ((Excel.Worksheet) this.Application.ActiveWorkbook.Sheets[1]). Copy(Type.Missing, this.Application.ActiveWorkbook.Sheets[3]);
// Fill across sheet method this.Application.ActiveWorkbook.Sheets.FillAcrossSheets( this.Application.get_Range("Data", Type.Missing), Excel.XlFillWith.xlFillWithAll);
// move Worksheet Excel.Sheets shts = this.Application.ActiveWorkbook.Sheets; ((Excel.Worksheet)shts[1]).Move(Type.Missing, shts[shts.Count]);
// print out method ((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[1]). PrintOut(1, 1, 2, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Workbook類的方法 Workbook代表一個工作簿,他也提供了很多方法,其中一些方法用來處理一些非常特殊的場景。和前面介紹其他對象一樣,這里僅介紹我們在開發(fā)中會經(jīng)常使用到的屬性和方法。
// Active a workbook ((Excel._Workbook)this.Application.Workbooks[1]).Activate();
// Close a workbook without save changes this.Application.Workbooks[1].Close(false,Type.Missing, Type.Missing);
// Protect a workbook use password this.Application.Workbooks[1].Protect("your password", Type.Missing, Type.Missing);
// Save all open workbooks. foreach (Excel.Workbook wb in this.Application.Workbooks) { wb.Save(); }
// Save as the active workbook this.Application.ActiveWorkbook.SaveAs("C:\\MyWorkbook.xml", Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// save a copy of the activeworkbooks this.Application.ActiveWorkbook.SaveCopyAs("C:\\Test.xls");
四 Worksheet類雖然Worksheet類也提供了大量的屬性方法和事件,但是大部分的屬性和方法和Application和Workbook類現(xiàn)相似,這部分重點(diǎn)介紹Worksheet中之前的對象中沒有講到過的,且經(jīng)常會用到的屬性和方法。 沒有Sheet類 雖然Workbook對象有一個Sheets集合類,但是并不存在一個所謂的Sheet類,Sheets集合中的類要不是Worksheet元素,要么是Chart對象??梢哉J(rèn)為Worksheet和Chart對象是Sheet類對象的實(shí)例,雖然公共的對象中并沒有看到有Sheet類。 文檔保護(hù) 通常Excel會對工作簿或者工作表提供一些保護(hù)特性,以不允許用戶修改工作表中的隊形。一旦我們開啟了對工作表進(jìn)行保護(hù),除非進(jìn)行取消保護(hù),否則用戶不能編輯或者修改工作表。在用戶界面上,您可以通過菜單審閱-> 保護(hù)工作表菜單開啟,我們可以設(shè)置保護(hù)密碼。默認(rèn)情況下,會對所有的工作表中的單元格進(jìn)行保護(hù)。如果您要對特定范圍的單元格進(jìn)行保護(hù),可能需要使用 審閱->允許用戶編輯區(qū)域?qū)崿F(xiàn)。 在代碼中,我們可以通過調(diào)用Worksheet的Protect方法來實(shí)現(xiàn),該方法有很多參數(shù)進(jìn)行配置。其方法簽名如下: // Worksheet protect method signature
WorksheetObject.Protect(Password, DrawingObjects, Contents,
Scenarios, UserInterfaceOnly, AllowFormattingCells,
AllowFormattingColumns, AllowFormattingRows,
AllowInsertingColumns, AllowInsertingRows,
AllowInsertingHyperlinks, AllowDeletingColumns,
AllowDeletingRows, AllowSorting, AllowFiltering,
AllowUsingPivotTables);
下面是一個使用Protect方法對工作表進(jìn)行保護(hù)的例子,該方法設(shè)置了保護(hù)密碼,并僅允許對數(shù)據(jù)進(jìn)行排序: ((Excel.Worksheet)this.Application.Sheets[1]).Protect( "MyPassword", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing); 要取消保護(hù),直接調(diào)用unprotect方法即可。 Object屬性 Worksheet對象還有幾個返回Object類型的屬性。
下面的代碼演示了如果注釋存在,刪除,然后添加注釋。后面演示了如何通過代碼演示和現(xiàn)實(shí)所有注釋: Excel.Range rng = this.Application.get_Range("Date", Type.Missing); if (rng.Comment != null) { rng.Comment.Delete(); } rng.AddComment("Comment added " + DateTime.Now); // Display all the comments: ShowOrHideComments(true); Worksheet類提供了Comments屬性,該屬性返回一個Comments對象,該對象是一個集合,您可以便利該集合中的對象,Comment類提供的屬性很少,用的最多的是Visible屬性,用來顯示或者隱藏注釋;在一個就是Delete屬性,用來刪除注釋,最后Text屬性可以用來添加或者修改現(xiàn)有的注釋。 添加完成注釋之后,我們可能希望在工作表中顯示注釋。下面就是在當(dāng)前活動工作表中顯示或者隱藏注釋的代碼。 private void ShowOrHideComments(bool show) { // Show or hide all the comments: Excel.Worksheet ws = (Excel.Worksheet)this.Application.Sheets["Worksheet Class"]; for (int i = 1; i <= ws.Comments.Count; i++) { ws.Comments[i].Visible = show; } } 五 Range對象Range對象是在Excel開發(fā)中用的最多的隊形,在我們對Excel進(jìn)行操作之前,我們需要獲取我們要進(jìn)行操作的對象。幾乎我們對工作表中的內(nèi)容操作都會涉及到Range對象。Range對象是對工作表中內(nèi)容的一種抽象,他可以表示一個單元格,一行數(shù)據(jù),一列數(shù)據(jù),一個選擇的單元格區(qū)間,或者在不同工作表中的一系列對象。下圖是Range的簡要對象模型圖:
下面就從三個方面介紹Range對象
對選中對象進(jìn)行操作 雖然可以對當(dāng)前選中的對象進(jìn)行各種屬性和行為的修改,但是最好避免這樣做。Excel中的選中對象代表用戶的選擇。如果我們再代碼中進(jìn)行修改的話,會導(dǎo)致用戶對當(dāng)前選中的對象失去控制。首要準(zhǔn)則是,只有當(dāng)你試圖更改用戶的選擇區(qū)域時,才去調(diào)用Range對象的Select方法。作為一個開發(fā)者,我們不應(yīng)該因?yàn)樵摲椒ū容^簡單就去使用它。如果我們只想對這些用戶選中的范圍進(jìn)行操作的話,通常有其他更好的選擇。避免調(diào)用Select方法不僅能夠使得我們的代碼運(yùn)行的更快,而且也能讓用戶更高興使用我們的產(chǎn)品。 下面的代碼用來清除用戶當(dāng)前單元格中的內(nèi)容。 // clear select content this.Application.ActiveCell.CurrentRegion.Select(); ((Excel.Range)this.Application.Selection).ClearContents(); 上面的代碼會使得用戶當(dāng)前的選擇區(qū)域丟失。如果之前只有一個單元格被選中,那么在運(yùn)行上面的代碼之后,整個連續(xù)的單元格都回被選中了。除非我們的目的就是這樣,要選擇整個Range返回內(nèi)的單元格,一個更好的方法可能是: this.Application.ActiveCell.CurrentRegion.ClearContents();
之前的代碼通常是使用宏錄制獲得的,一般情況下,宏錄制其會錄制好用戶的選擇,然后對用戶的選擇進(jìn)行修改。當(dāng)我們對單個單元格或者多個單元格進(jìn)行操作的時候,一般應(yīng)該使用Range對象來表示我們操作的對象,而不是通過修改選中的對象來進(jìn)行操作。如果確實(shí)需要修改用戶的選擇對象,可以使用Range.Select 方法。 在代碼中引用Range對象 在開發(fā)中,Range對象的使用范圍非常廣泛和靈活。有時候Range對象表示單個的對象,有時候也表示一個集合。即使一個Range對象只表示一個對象,它也有Item和Count屬性,所以我們要注意在有些情況下該如何更好地使用Range對象。
Excel.Worksheet ws = (Excel.Worksheet)this.Application.Worksheets[1]; Excel.Range rng1, rng2; rng1 = this.Application.ActiveCell;
rng = ws.get_Range("A1", Type.Missing); rng = ws.get_Range("A1:B12", Type.Missing);
rng = (Excel.Range)ws.Cells[1, 1];
rng = ws.get_Range("A1", "C5"); rng = ws.get_Range("A1", "C5").Cells; rng = ws.get_Range("A1", "C5").Rows; rng = ws.get_Range("A1", "C5").Columns;
rng = this.Application.get_Range("SomeRangeName", Type.Missing);
rng = (Excel.Range)ws.Rows[1, Type.Missing]; rng = (Excel.Range)ws.Rows["1:3", Type.Missing]; rng = (Excel.Range)ws.Columns[3, Type.Missing];
// C# rng = this.Application.get_Range("A1:D4, F2:G5", Type.Missing); // You can also use the Application object's Union // method to retrieve the intersection of two ranges, but this // is far more effort in C#: rng1 = this.Application.get_Range("A1", "D4"); rng2 = this.Application.get_Range("F2", "G5"); // Note that the Union method requires you to supply thirty // parameters: rng = this.Application.Union(rng1, rng2, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
rng = this.Application.get_Range("A1:D16 B2:F14", Type.Missing); // You can also use the Application object's Intersect // method to retrieve the intersection of two ranges. Note // that the Intersect method requires you to pass 30 parameters: rng1 = this.Application.get_Range("A1", "D16"); rng2 = this.Application.get_Range("B2", "F14"); rng = this.Application.Intersect(rng1, rng2, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
rng = (Excel.Range)ws.Cells[1, 1]; for (int i = 1; i <= 5; i++) { rng.get_Offset(i, 0).Value2 = i.ToString(); }
Excel.Range rngLeft, rngRight, rngUp, rngDown; rng = (Excel.Range)this.Application.Selection; // Note that the Range.End property is parameterized, so // C# developers cannot retrieve it. You must call the // get_End method, instead: // E3 rngRight = rng.get_End(Excel.XlDirection.xlToRight); // A3 rngLeft = rng.get_End(Excel.XlDirection.xlToLeft); // C1 rngUp = rng.get_End(Excel.XlDirection.xlUp); // C5 rngDown = rng.get_End(Excel.XlDirection.xlDown);
操作Range對象 獲得了Range對象之后,我們就可以對Range對象進(jìn)行各種操作了。
private void AutoFill() { Excel.Range rng = this.Application.get_Range("B1", Type.Missing); rng.AutoFill(this.Application.get_Range("B1:B5", Type.Missing), Excel.XlAutoFillType.xlFillDays); rng = this.Application.get_Range("C1", Type.Missing); rng.AutoFill(this.Application.get_Range("C1:C5", Type.Missing), Excel.XlAutoFillType.xlFillMonths); rng = this.Application.get_Range("D1", Type.Missing); rng.AutoFill(this.Application.get_Range("D1:D5", Type.Missing), Excel.XlAutoFillType.xlFillYears); rng = this.Application.get_Range("E1:E2", Type.Missing); rng.AutoFill(this.Application.get_Range("E1:E5", Type.Missing), Excel.XlAutoFillType.xlFillSeries); }
Find方法有很多個參數(shù),下面的代碼演示了如何使用Find方法: private void DemoFind() { Excel.Range rng = this.Application. get_Range("Fruits", Type.Missing); Excel.Range rngFound; // Keep track of the first range you find. Excel.Range rngFoundFirst = null; // You should specify all these parameters // every time you call this method, since they // can be overriden in the user interface. rngFound = rng.Find("apples", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); while (rngFound != null) { if (rngFoundFirst == null) { rngFoundFirst = rngFound; } else if (GetAddress(rngFound) == GetAddress(rngFoundFirst)) { break; } rngFound.Font.Color = ColorTranslator.ToOle(Color.Red); rngFound.Font.Bold = true; rngFound = rng.FindNext(rngFound); } }
下面的代碼演示了自定義排序: private void DemoSort() { Excel.Range rng = this.Application. get_Range("Fruits", Type.Missing); rng.Sort(rng.Columns[1, Type.Missing], Excel.XlSortOrder.xlAscending, rng.Columns[2, Type.Missing], Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlNo, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal); } 六 結(jié)語要進(jìn)行Excel開發(fā),繞不開對Excel中對象模型的理解, 本文簡要介紹了Excel中的對象模型,介紹了這些對象中比較重要的幾個對象,Application,Workbook,Worksheet,Range對象,這些對象不論在何種Excel開發(fā)方式中,只要需要對Excel進(jìn)行交互,都會使用的到,本文介紹了這四個對象中的一些常用的屬性,方法及事件。他們之間有很多對象都有相同的屬性方法或者事件,這篇文章主要是想讓大家對Excel對象模型有一個簡單的認(rèn)識,具體全部的對象模型,大家可以直接到MSDN或者Google上面去查找,下一篇文章將會介紹Excel中比較核心的功能:自定義函數(shù)。 希望本文對大家理解Excel對象模型有所幫助。 |
|
|