C#操作Excel(1)Excel对象模型
Excel對(duì)象模型? (.Net Perspective)
本文主要針對(duì)在Visual Studio中使用C#?開(kāi)發(fā)關(guān)于Excel的應(yīng)用程序
本文的PDF下載地址:C#操作Excel2007.pdf
來(lái)源:Understandingthe Excel Object Model from a .NET Developer's Perspective
Excel對(duì)象模型中的四大主要對(duì)象: Application Excel應(yīng)用程序本身 Workbook? 工作表Sheet的集合 Worksheet ? ? ? ? ? ? ? 一個(gè)工作表Sheet Range ? ? ? ? ? ? ? ? ? ??表示一塊區(qū)域所有Excel對(duì)象請(qǐng)參考MSDN:
ExcelObject Model Reference
----------------------------------------------華麗分割-------------------------------------------------
1.???????Application?
首先討論Application對(duì)象,Application對(duì)象的成員大概可以分成5大類
?
- l? 控制Excel的狀態(tài)與顯示
- l? 返回對(duì)象
- l? 執(zhí)行Action
- l? 控制文件操作(handle file manipulation)
- l? 其他
?
?
1.1 Application成員之:控制Excel的狀態(tài)與顯示
| Property | Type | Description |
| Cursor | XlMousePointer (xlDefault, xlIBeam, xlNorthwestArrow, xlWait) | 設(shè)置/取得 鼠標(biāo)指針的Appearence |
| EditDirectlyInCell | Boolean | Gets or sets the ability to edit cells directly in place. If False, you can only edit cells in the formula bar. |
| FixedDecimal | Boolean | If?True, all numeric values use the?FixedDecimalPlacesproperty to determine the number of decimal places; otherwise,?FixedDecimalPlaces?property is ignored (the default value is False). |
| FixedDecimalPlaces | Long | Determines the number of decimal places to be used for numeric data if the?FixedDecimal?property is True. |
| Interactive | Boolean | Gets or sets the ability of the user to interact with Excel via the keyboard and mouse; if you set this property to False, make absolutely sure you set it back to True in your exception handler. Excel won't reset it for you. |
| MoveAfterReturn | Boolean | 如果為真,表示按下回車鍵后移動(dòng)到下一個(gè)單元格 |
| MoveAfterReturnDirection | xlDirection (xlDown, xlToLeft, xlToRight, xlUp) | 設(shè)置按下回車鍵后,單元格focus的移動(dòng)方向,( 僅在MoveAfterReturn?屬性為真時(shí)有效) 默認(rèn)移動(dòng)方向:xlDown. |
| ScreenUpdating | Boolean | If True, Excel updates its screen after each method call. To save time, and to make your application look more professional,you can turn off the display while your code is running. Make sure you reset this property to True again once you're done. Excel won't reset it for you. |
| SheetsInNewWorkbook | Long | Gets or sets the number of sheets Excel automatically places in new workbooks |
| StandardFont | String | Gets or sets the name of the default font in Excel; doesn't take effect until you restart Excel. |
| StandardFontSize | Long | Gets or sets the size of the default font in Excel; doesn't take effect until you restart Excel. |
| StartupPath (read-only | String | Returns the complete path of the folder containing the Excel startup add-ins. |
| TemplatesPath (read-only) | String | Returns the complete path of the folder containing templates; this value represents one of the Windows special folders. |
?
上面列出的屬性中,比較重要的是:ScreenUpdating
它的含義是:是否在任一函數(shù)執(zhí)行完成后更新Excel的界面顯示。如果你在進(jìn)行大數(shù)據(jù)量的計(jì)算,這一功能盡量關(guān)閉,因?yàn)檫@可以提高你的任務(wù)執(zhí)行速度。
ScreenUpdating在C#中的使用方法是:(執(zhí)行完任務(wù)記得重新開(kāi)啟該功能)
?
[csharp]?view plaincopy?
下面再介紹幾個(gè)有關(guān)屬性:
| Property | Type | Description |
| DisplayAlerts | Boolean | If True (the default value), Excel displays warning messages while your code runs, as necessary--when deleting a sheet, for example. Set to False to bypass warnings. Excel acts as if you had selected the default value for each alert. |
| DisplayFormulaBar | Boolean | If True (the default value), Excel displays the standard formula bar for editing cells; set to False to hide the editing bar. |
| DisplayFullScreen | Boolean | If True, Excel runs in full-screen mode (which has a different effect from simply maximizing the Excel window); the default value is False. |
?
1.2?Application成員之:?who return objects
Excel庫(kù)包含很多類,但是在Visual Studio中提供給開(kāi)發(fā)人員的只有Excel.Application,Workbook等,那么我們?cè)趺传@得其他很多有用的類型呢?
????? 比如,我想獲得當(dāng)前活動(dòng)的單元格(cell),怎么辦?不用擔(dān)心,Application對(duì)象提供很多屬性能夠返回其他很多類型的對(duì)象的引用。下面具體來(lái)看一下:
| Property | Type | Description |
| ActiveCell | Range | Returns a reference to the currently active cell in the active window (the window that's on top). If there's no active window, this property raises an error. |
| ActiveChart | Chart | Returns a reference to the currently active chart. An embedded chart is only considered active when it's selected or activated. |
| ActiveSheet | Object | Returns a reference to the active sheet in the active workbook. |
| ActiveWindow | Window | Returns a reference to the active window (the window that's on top); returns Nothing if there are no active windows. |
| Charts | Sheets | Returns a collection of?Sheet?objects (the parent for bothChart?and?Worksheet?objects) containing references to each of the charts in the active workbook. |
| Selection | Object | Returns the selected object within the application. Might be a?Range, a?Worksheet, or any other object—also applies to the?Window?class, in which case the selection is generally a?Range?object. If no object is currently selected, returns Nothing. |
| Sheets | Sheets | Returns a collection of?Sheet?objects containing references to each of the sheets in the active workbook. |
| Workbooks | Workbooks | Returns a collection of?Workbook?objects containing references to all the open workbooks. |
上面的屬性中,Workbooks屬性無(wú)疑是最常用的。通過(guò)這個(gè)屬性,我們可以打開(kāi)或者創(chuàng)建一個(gè)workbook,下面我們具體看一下該屬性的一些行為。
1.????創(chuàng)建workbook
?
[csharp]?view plaincopy?
2.????關(guān)閉workbook
?
[csharp]?view plaincopy?
3.????打開(kāi)一個(gè)存在的workbook
?
[csharp]?view plaincopy?
4.????用Excel的方式打開(kāi)XML文件,數(shù)據(jù)庫(kù)文件或者TXT文件
OpenXML,OpenDatabase,OpenText
?
5.????通過(guò)名字或者索引引用workbook
?
[csharp]?view plaincopy1.3?Application成員之:?Execute Actions
這類成員包括Calculate,CheckSpelling,Evaluate,Sendmaid,Undo,Quit。。。實(shí)在是太多了,請(qǐng)參考原文。
?
1.4?Application成員之:?Handles File Manipulation
l? 缺省文件路徑??????????? DefaultFilePath
?
[csharp]?view plaincopy?
l? 默認(rèn)的保存文件格式 DefaultSaveFormat
下圖展示了Excel支持的保存文件格式
?
[csharp]?view plaincopy?
l? RecentFiles屬性
?
[csharp]?view plaincopy?
?
l? FileDialog屬性
Using this dialog box, you cantake advantage of all the file handling capabilities provided by MicrosoftOffice.
The?FileDialog?property requires that you select aparticular use of the dialog box by passing it one of themsoFileDialogType?enumerated values:
msoFileDialogFilePicker,?
msoFileDialogFolderPicker,?
msoFileDialogOpen, or?
msoFileDialogSaveAs.?
You can then interact with the?FileDialog?object returned by the property.
使用該屬性需要引用Microsoft.Office.Core 命名空間
?
[csharp]?view plaincopy?
執(zhí)行打開(kāi)文件對(duì)話框的show()函數(shù),將顯示該對(duì)話框。用戶點(diǎn)擊OK,則該函數(shù)返回-1,若點(diǎn)擊Cancel,則該函數(shù)返回0。
?
[csharp]?view plaincopy?
大致包括以下幾類:(具體請(qǐng)參考MSDN)
?
- WorksheetFunctionClass
- WindowClass & Window Collection
- NameClass & Name Collection
- ApplicationEvent
?
------------------------------------華麗分割------------------------------------?
2. Workbook
該類提供約90個(gè)屬性。很多是開(kāi)發(fā)者想象不到的屬性,比如:
?
- AutoUpdateFrequency 返回一個(gè)共享的workbook的自動(dòng)更新間隔時(shí)間
- Date1904 返回true表示當(dāng)前使用的是data 1904 時(shí)間系統(tǒng)
- PasswordEncryptionAlgorithm允許你設(shè)置加密算法。
?
下面給出最常使用的Workbook屬性
?
- ? Name,Fullname ,Path
?
?
?
- Password(給EXCEL文件加密)
?
?
- PrecisionAsDisplayed
?
?
?
- ReadOnly? (boolean)??? 返回當(dāng)前打開(kāi)的文件是否是只讀的
- ? Saved? ????? (boolean)??? 設(shè)置/獲取 saved state
?
Working with Styles?
?
[csharp]?view plaincopy?
設(shè)置風(fēng)格后的樣子:
當(dāng)然,設(shè)置Style后也可以清除Style
?
[csharp]?view plaincopy?
Working with Sheets
?
[csharp]?view plaincopy?
?
----------------------------------------------華麗分割-----------------------------------------------3. WorkSheet
當(dāng)你閱讀到這里的時(shí)候,你已經(jīng)了解了大部分關(guān)于worksheet的概念。盡管Worksheet類提供了大量屬性,方法,事件;但其實(shí)它們的實(shí)現(xiàn)方法基本與Application和Workbook中的實(shí)現(xiàn)方法相同。這一節(jié)著重介紹之前沒(méi)有討論的內(nèi)容。3.1?There is no Sheet Class..?
什么?沒(méi)有Sheet類?
????? 我們知道,Workbook對(duì)象有一個(gè)屬性叫做Sheets,它是一個(gè)Workbook中Sheet的集合,但Excel中確實(shí)沒(méi)有叫做Sheet的類。取而代之的是,Sheets集合中的每一個(gè)元素都是一個(gè)WorkSheet對(duì)象或者Chart對(duì)象。你可以這樣去想: Worksheet以及Chart類都是specialized instances of an internal Sheet Class
?
3.2? Working with Protection
通常,protection特性用于防止用戶修改worksheet中的對(duì)象。一旦你使能了worksheet的protection功能,那么用戶將無(wú)法編輯&修改該sheet。在用戶界面,你可以選擇Tools | Protection | ProtectSheet(Excel2007下面是 審閱 | 更改 | 保護(hù)工作表)來(lái)使能protection。如下圖所示:?
你也可以定義允許用戶編輯的區(qū)域:
通過(guò)以上兩個(gè)對(duì)話框,你就可以鎖定sheet,同時(shí)允許用戶編輯指定的選項(xiàng)以及區(qū)域(edit specificfeatures and ranges)。
當(dāng)然,上述的內(nèi)容也可以讓C#幫我們完成。
?
[csharp]?view plaincopy?
?
上面的Protect方法有很多參數(shù),分別對(duì)應(yīng)保護(hù)的內(nèi)容。
?
- Password??對(duì)應(yīng)密碼,當(dāng)你要撤銷保護(hù)時(shí)需要指定密碼
- DrawingObjects????保護(hù)Shapes on the worksheet
- Contents?????????保護(hù)cells,即所有單元格內(nèi)容
- Scenarios????????保護(hù)情景
- UserInterfaceOnly????? 允許通過(guò)代碼修改,不允許通過(guò)用戶界面修改AllowFormattingCells AllowFormattingColumns….后面不再贅述
?
下面這個(gè)例子,設(shè)置了密碼,同時(shí)只允許Sorting
?
[csharp]?view plaincopy?
下面的代碼展示如何去保護(hù)(提示讓用戶輸入密碼)
?
[csharp]?view plaincopy?
除此之外,Protection還提供了AllowEditRanges屬性,可以讓你指定可編輯的范圍。AllowEditRanges屬性是AllowEditRange對(duì)象的集合,每一個(gè)對(duì)象都提供了一些有用的屬性,比如:
?
- l? Range?????? get/set range of the editable area
- l? Title????????? get/set the title of the editableregion
- l? Users???????? get/set a collection of UserAccessobject
?
下面這個(gè)例子演示了Protection的功能,當(dāng)你點(diǎn)擊Protect時(shí),你只能編輯陰影區(qū)域,點(diǎn)擊Unprotect可以去保護(hù)。
代碼如下:(對(duì)應(yīng)點(diǎn)擊圖中的鏈接(Protect,Unprotect)執(zhí)行的代碼)
?
[csharp]?view plaincopy?
Worksheet類提供了一些屬性(that return objects),下面介紹兩個(gè)有用屬性:
Comments以及Outline
3.3.1 ?Comments (批注)
在Excel2007中,選中一塊區(qū)域或者單元格后,點(diǎn)擊右鍵,可以插入批注。插入批注后的樣子如下圖所示
Worksheet類提供Comments屬性,通過(guò)該屬性,你可以訪問(wèn)該工作表內(nèi)的所有批注。Comments類沒(méi)有多少屬性,你可能會(huì)使用Visible屬性來(lái)控制批注的顯示與隱藏,Delete屬性來(lái)刪除批注,或者你可能會(huì)發(fā)現(xiàn)Text方法比較有用,因?yàn)榭梢酝ㄟ^(guò)它來(lái)給批注增加內(nèi)容或者重寫(xiě)批注。
下面是一個(gè)及其簡(jiǎn)單的例子,來(lái)控制顯示批注
?
[csharp]?view plaincopy?
Outline的功能是把row劃分成組,使得Excel的顯示更有層次感與結(jié)構(gòu)氣息。
例如,下面兩張圖片
左圖:創(chuàng)建Outline??????????????????????????? 右圖:折疊后效果
tline屬性本身是一個(gè)Outline對(duì)象,它自身屬性不多,主要有以下幾個(gè):
?
- l? AutomaticStyles???????? 告訴Excel是否應(yīng)用automatic style to outline
- l? SummaryColumn?????? get or set the location of the summarycolumns, (兩個(gè)選項(xiàng):? xlSummaryOnLeft? xlSummaryOnRight)
- l? SummaryRow??????????? get or set the location of thesummary rows,(兩個(gè)選項(xiàng):? xlSummaryAbove? xlSummaryBelow)
- l? ShowLevels??????????????? 允許你折疊/擴(kuò)展outline groups to the row level and/or column levelyou want.
?
經(jīng)過(guò)上面的介紹,你應(yīng)該對(duì)Outline有了基本的了解,下面開(kāi)始使用C#操作Outline。
首先是創(chuàng)建Group,創(chuàng)建Group是簡(jiǎn)單的,你可以調(diào)用range對(duì)象的Group()方法;調(diào)用Ungroup()方法移除Group。
?
[csharp]?view plaincopy?
對(duì)于unnamed range,方法如下:
?
[csharp]?view plaincopy?
在前面的圖片中點(diǎn)擊Clear Groups link將清除Groups,對(duì)應(yīng)代碼如下:
?
[csharp]?view plaincopy?
OK,通過(guò)上面的技巧,你就可以創(chuàng)建&移除groups了。同時(shí)你也可以控制工作表上顯示的group的層次了!
?
----------------------------------------------華麗分割-----------------------------------------------
?
4. Range
Range 對(duì)象將是你在開(kāi)發(fā)關(guān)于Excel的應(yīng)用程序中最經(jīng)常使用的,在你操作任何Excel中的區(qū)域之前,你都要使用一個(gè)Range對(duì)象來(lái)表示該區(qū)域,然后通過(guò)Range對(duì)象的方法和屬性來(lái)操作該區(qū)域。Range對(duì)象是如此的重要,以至于本文上述所有的例子幾乎都存在Range對(duì)象。通常,一個(gè)Range對(duì)象可以代表一個(gè)單元格,一行,一列,一塊區(qū)域(containing oneor more blocks of cells)甚至是一組在不同sheets中的單元格。
不幸的是,由于Range對(duì)象太大,成員太多,故不可能對(duì)其成員進(jìn)行逐一描述。所以,下面從三個(gè)比較重要的方面介紹Range對(duì)象
?
- l? 在代碼中引用ranges
- l? 在代碼中操作ranges
- l? 使用Range對(duì)象完成特定任務(wù)
?
????? Work with current selection 等價(jià)于修改當(dāng)前選中Range的屬性和行為,不過(guò)你最好避免這么做。因?yàn)?,selection within Excel代表著用戶的選擇。如果你修改了它,那么將導(dǎo)致用戶失去對(duì)“當(dāng)前選擇”的控制。關(guān)于selection,第一準(zhǔn)則是:you should call the Selectmethod only if your intent is to change the user’s selection.
例如,下面的代碼將清除用戶當(dāng)前選中單元格旁邊的單元格的內(nèi)容
?
[csharp]?view plaincopy?
4.2? Referring to a Range in Code
1)????基本的引用Range方法
1.???引用ActiveCell
?
[csharp]?view plaincopy?
2.???使用get_Range方法,指定Range范圍
?
[csharp]?view plaincopy?
3.???使用Cells屬性
?
[csharp]?view plaincopy?
4.???指定Range的角,同時(shí)可以直接引用該Range的Cells Rows Columns屬性
?
[csharp]?view plaincopy?
5.???引用一個(gè)帶名字的Range
?
[csharp]?view plaincopy?
6.???引用特定的行或者列
?
[csharp]?view plaincopy?
7.???使用Application對(duì)象的Selection方法獲取選中Cells對(duì)應(yīng)的Range
執(zhí)行下面代碼,將在調(diào)試窗口看到:"$C$3"
?
[csharp]?view plaincopy?
8.???兩個(gè)Range合并為一個(gè)Range
?
[csharp]?view plaincopy?
9.???Range的Offset屬性
?
[csharp]?view plaincopy?
?
10,11,12....100#$%^&**(&%$...太多了,不能一一介紹經(jīng)過(guò)上面的介紹,是不是有一點(diǎn)暈?zāi)?#xff1f;下面通過(guò)一個(gè)小例子來(lái)演示一下Range的功能吧。
??????在使用Excel中,我們可能希望在選中一個(gè)單元格后使整行加粗顯示,即實(shí)現(xiàn)選中效果,但是Excel中沒(méi)有對(duì)該功能的支持。但是,通過(guò)代碼不難實(shí)現(xiàn)該功能,首先看一下實(shí)際效果吧。
可以看到,選中的單元格所在行變成了Bold顯示。
其實(shí)現(xiàn)代碼如下:
?
[csharp]?view plaincopy?
下面的代碼verifies that the new selection is within the correct range using the?Intersect?method ofthe?Application?object
?
[csharp]?view plaincopy?
????? 一旦你獲得了一個(gè)Range的引用,你能做什么呢?答案是: Endless,as you can imagine。下面介紹兩個(gè)典型的場(chǎng)景。
4.3.1 Autimatically Filling Ranges自動(dòng)填充功能?? (AutoFill方法用于向一個(gè)范圍中填充遞增或者遞減的值)
首先看一下:XlAutoFillType? 枚舉類型
?
- l? xlFillDays
- l? ?xlFillFormats
- l? ?xlFillSeries
- l? xlFillWeekdays,
- l? xlGrowthTrend
- l? ?xlFillCopy
- l? ?xlFillDefault
- l? ?xlFillMonths
- l? ?xlFillValues
- l? ?xlFillYears
- l? xlLinearTrend
?
?
[csharp]?view plaincopy?
?
4.3.2 Searching Within RangesRange類的Find方法允許你在Range中進(jìn)行搜索。當(dāng)然你也可以再Excel界面中使用Ctrl+F打開(kāi)搜索對(duì)話框,如下圖所示
下表列出了Range.Find方法的參數(shù)
| What (required) | Object | The data to find; can be a string or any Excel data type. |
| After | Range | The range after which you want the search to start (this cell won't be included in the search); if you don't specify this cell, the search begins in the upper-left corner of the range. |
| LookIn | XlFindLookin (xlValue, xlComments, xlFormulas) | The type of information to be searched; cannot be combined using the Or operator. |
| LookAt | XlLookAt (xlWhole, xlPart) | Determines whether the search matches entire cells, or partial cells. |
| SearchOrder | XlSearchOrder (xlByRows, xlByColumns) | Determines the order for the search; xlByRows (the default) causes the search to go across and then down, and xlByColumns causes the search to go down and then across. |
| SearchDirection | XlSearchDirection (xlNext, xlPrevious) | Determines the direction of the search; the default is xlNext. |
| MatchCase | Boolean | Determines whether the search is case-sensitive. |
| MatchByte | Boolean | Determines whether double-byte characters match only double-byte characters (True) or equivalent single-byte characters (False); only applies if you've installed double-byte support. |
?
不難看出,我們要搜索apples。下面是其實(shí)現(xiàn)的代碼:
?
[csharp]?view plaincopy?
若要取消查找后的顯示效果:
[csharp]?view plaincopy?
-----------------------------------------華麗分割-----------------------------------
OK,終于寫(xiě)完了。本文主要介紹了Excel的幾大對(duì)象,主要介紹的是一些API。后面將會(huì)通過(guò)實(shí)例,結(jié)合 VS2010,用C#來(lái)實(shí)現(xiàn)對(duì)Excel的操作。感謝閱讀。
?
-------------------------------------------------------------------------------------
本文的PDF版本下載:點(diǎn)此下載
轉(zhuǎn)載于:https://www.cnblogs.com/gc2013/p/3934957.html
總結(jié)
以上是生活随笔為你收集整理的C#操作Excel(1)Excel对象模型的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 点云 数据 (偏向于研究大小)
- 下一篇: C#中用委托实现C++的回调函数