日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C#操作Excel(1)Excel对象模型

發布時間:2023/12/20 C# 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#操作Excel(1)Excel对象模型 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Excel對象模型? (.Net Perspective)

本文主要針對在Visual Studio中使用C#?開發關于Excel的應用程序

本文的PDF下載地址:C#操作Excel2007.pdf

來源:Understandingthe Excel Object Model from a .NET Developer's Perspective

Excel對象模型中的四大主要對象: Application Excel應用程序本身 Workbook? 工作表Sheet的集合 Worksheet ? ? ? ? ? ? ? 一個工作表Sheet Range ? ? ? ? ? ? ? ? ? ??表示一塊區域

所有Excel對象請參考MSDN:

ExcelObject Model Reference

----------------------------------------------華麗分割-------------------------------------------------

1.???????Application?

首先討論Application對象,Application對象的成員大概可以分成5大類

?

  • l? 控制Excel的狀態與顯示
  • l? 返回對象
  • l? 執行Action
  • l? 控制文件操作(handle file manipulation)
  • l? 其他

?

?

1.1 Application成員之:控制Excel的狀態與顯示

Property

Type

Description

Cursor

XlMousePointer (xlDefault, xlIBeam, xlNorthwestArrow, xlWait)

設置/取得 鼠標指針的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

如果為真,表示按下回車鍵后移動到下一個單元格

MoveAfterReturnDirection

xlDirection (xlDown, xlToLeft, xlToRight, xlUp)

設置按下回車鍵后,單元格focus的移動方向,( 僅在MoveAfterReturn?屬性為真時有效) 默認移動方向: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

它的含義是:是否在任一函數執行完成后更新Excel的界面顯示。如果你在進行大數據量的計算,這一功能盡量關閉,因為這可以提高你的任務執行速度。

ScreenUpdating在C#中的使用方法是:(執行完任務記得重新開啟該功能)

?

[csharp]?view plaincopy
  • //?C#??
  • try??
  • {??
  • ???ThisApplication.ScreenUpdating?=?false;??
  • ???//?Do?your?work?that?updates?the?screen.??
  • }??
  • ???
  • finally??
  • {??
  • ???ThisApplication.ScreenUpdating?=?true;??
  • }??
  • ???
  • ?

    下面再介紹幾個有關屬性:

    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庫包含很多類,但是在Visual Studio中提供給開發人員的只有Excel.Application,Workbook等,那么我們怎么獲得其他很多有用的類型呢?

    ????? 比如,我想獲得當前活動的單元格(cell),怎么辦?不用擔心,Application對象提供很多屬性能夠返回其他很多類型的對象的引用。下面具體來看一下:

    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屬性無疑是最常用的。通過這個屬性,我們可以打開或者創建一個workbook,下面我們具體看一下該屬性的一些行為。

    1.????創建workbook

    ?

    [csharp]?view plaincopy
  • Excel.Workbook?wb?=?ThisApplication.Workbooks.Add(Type.Missing);??
  • ??

    ?

    2.????關閉workbook

    ?

    [csharp]?view plaincopy
  • ThisApplication.Workbooks.Close();??
  • ?

    3.????打開一個存在的workbook

    ?

    [csharp]?view plaincopy
  • Excel.Workbook?wb?=?ThisApplication.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);??
  • ?

    4.????用Excel的方式打開XML文件,數據庫文件或者TXT文件

    OpenXML,OpenDatabase,OpenText

    ?

    5.????通過名字或者索引引用workbook

    ?

    [csharp]?view plaincopy
  • Excel.Workbook?wb?=?ThisApplication.Workbooks[1];??
  • wb?=?ThisApplication.Workbooks["Book1"];//在workbook未保存的情況下??
  • wb?=?ThisApplication.Workbooks["Book1.xls"];//在workbook已經保存的情況下??
  • 1.3?Application成員之:?Execute Actions

    這類成員包括Calculate,CheckSpelling,Evaluate,Sendmaid,Undo,Quit。。。實在是太多了,請參考原文。

    ?

    1.4?Application成員之:?Handles File Manipulation

    l? 缺省文件路徑??????????? DefaultFilePath

    ?

    [csharp]?view plaincopy
  • //?C#??
  • //?When?the?workbook?opens:??
  • ThisApplication.get_Range("DefaultFilePath",?Type.Missing).??
  • ????Value2?=?ThisApplication.DefaultFilePath;??
  • ???
  • //?When?you?save?the?DefaultFilePath?property:??
  • ThisApplication.DefaultFilePath?=???
  • ????ThisApplication.get_Range("DefaultFilePath",?Type.Missing).??
  • ????Value2.ToString();??
  • ?

    l? 默認的保存文件格式 DefaultSaveFormat

    下圖展示了Excel支持的保存文件格式

    ?

    [csharp]?view plaincopy
  • //?例1??
  • //?When?the?workbook?opens,?convert?the?enumerated?value???
  • //?into?a?string:??
  • //獲得默認的保存格式屬性DefaultSaveFormat??
  • ThisApplication.get_Range("DefaultSaveFormat",?Type.Missing).??
  • ????Value2?=?ThisApplication.DefaultSaveFormat.ToString();??
  • ???
  • ???
  • //例2.設置該屬性,相對比較復雜??
  • //?步驟1.Retrieve?the?name?of?the?new?save?format,?as?a?string:??
  • string??strSaveFormat?=?ThisApplication.??
  • ??get_Range("DefaultSaveFormat",?Type.Missing).??
  • ??Value2.ToString();??
  • ???
  • //步驟2??
  • Excel.Range?rng?=?ThisApplication.??
  • ????get_Range("xlFileFormat",?Type.Missing);??
  • Excel.Range?rngFind?=?rng.Find(strSaveFormat,???
  • ????Type.Missing,?Type.Missing,?Type.Missing,?Type.Missing,???
  • ????Excel.XlSearchDirection.xlNext,?Type.Missing,?Type.Missing,???
  • Type.Missing);??
  • ???
  • //?In?C#,?use?the?get_Offset?method?instead?of?the?Offset?property:??
  • int?intSaveFormat?=???
  • Convert.ToInt32(rngFind.get_Offset(0,?1).Value2);??
  • ???
  • //步驟3.??
  • ThisApplication.DefaultSaveFormat?=???
  • ??Excel.XlFileFormat)?intSaveFormat;??
  • ?

    l? RecentFiles屬性

    ?

    [csharp]?view plaincopy
  • //?列出最近打開的文檔<strong>??
  • </strong>private?void?ListRecentFiles()??
  • {??
  • ????Excel.Range?rng?=?(Excel.Range)ThisApplication.??
  • ????????get_Range("RecentFiles",?Type.Missing).Cells[1,?1];??
  • ???
  • ????for?(int?i?=?1;?i?<=?ThisApplication.RecentFiles.Count;?i++)??
  • ????{??
  • ????????rng.get_Offset(i?-?1,?0).Value2?=???
  • ????????????ThisApplication.RecentFiles[i].Name;??
  • ????}???
  • }??
  • ?

    ?

    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
  • //?C#??
  • using?Office?=?Microsoft.Office.Core;??
  • ?

    執行打開文件對話框的show()函數,將顯示該對話框。用戶點擊OK,則該函數返回-1,若點擊Cancel,則該函數返回0。

    ?

    [csharp]?view plaincopy
  • //?打開FileDialog,選擇一個文件打開??
  • dlg?=?ThisApplication.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();??
  • 1.5?Application成員之:?其他

    ?

    大致包括以下幾類:(具體請參考MSDN)

    ?

    • WorksheetFunctionClass
    • WindowClass & Window Collection
    • NameClass & Name Collection
    • ApplicationEvent

    ?

    ------------------------------------華麗分割------------------------------------

    ?

    2. Workbook

    該類提供約90個屬性。很多是開發者想象不到的屬性,比如:

    ?

    • AutoUpdateFrequency 返回一個共享的workbook的自動更新間隔時間
    • Date1904 返回true表示當前使用的是data 1904 時間系統
    • PasswordEncryptionAlgorithm允許你設置加密算法。

    ?

    下面給出最常使用的Workbook屬性

    ?

    • ? Name,Fullname ,Path
    [csharp]?view plaincopy
  • ThisApplication.get_Range("WorkbookName",?Type.Missing).??
  • ????Value2?=?ThisWorkbook.Name;??
  • ThisApplication.get_Range("WorkbookPath",?Type.Missing).??
  • ????Value2?=?ThisWorkbook.Path;??
  • ThisApplication.get_Range("WorkbookFullName",?Type.Missing).??
  • ????Value2?=?ThisWorkbook.FullName;??
  • ?

    ?

    ?

    • Password(給EXCEL文件加密)
    [csharp]?view plaincopy
  • private?void?SetPassword()??
  • {??
  • ????Password?frm?=?new?Password();??
  • ???
  • ????if?(frm.ShowDialog()?==?DialogResult.OK)??
  • ????????ThisWorkbook.Password?=?frm.Value;??
  • ????frm.Dispose();??
  • }??
  • ?

    ?

    • PrecisionAsDisplayed
    [csharp]?view plaincopy
  • private?void?TestPrecisionAsDisplayed(??
  • ????bool?IsPrecisionAsDisplayedOn)??
  • {??
  • ????ThisWorkbook.PrecisionAsDisplayed?=???
  • ????????IsPrecisionAsDisplayedOn;??
  • }??
  • ?

    ?

    ?

    • ReadOnly? (boolean)??? 返回當前打開的文件是否是只讀的
    • ? Saved? ????? (boolean)??? 設置/獲取 saved state

    ?

    Working with Styles?

    ?

    [csharp]?view plaincopy
  • //?風格設置??
  • 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?=?ThisWorkbook.Styles[STYLE_NAME];??
  • ????}??
  • ????catch??
  • ????{??
  • ????????sty?=?ThisWorkbook.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();??
  • }??
  • ???
  • ???
  • private?Excel.Range?GetDocPropRange()??
  • {??
  • ????Excel.Range?rng?=???
  • ????????ThisApplication.get_Range("DocumentProperties",?Type.Missing);??
  • ???
  • ????Excel.Range?rngStart?=???
  • ????????(Excel.Range)?rng.Cells[1,?1];??
  • ???
  • ????Excel.Range?rngEnd?=???
  • ????????rng.get_End(Excel.XlDirection.xlDown).get_Offset(0,?1);??
  • ???
  • ????return?ThisApplication.get_Range(rngStart,?rngEnd);??
  • }??
  • ???
  • ?

    設置風格后的樣子:

    當然,設置Style后也可以清除Style

    ?

    [csharp]?view plaincopy
  • //?C#??
  • private?void?ClearStyle()??
  • {??
  • ????//?Get?the?range?containing?all?the?document?properties,?and??
  • ????//?clear?the?style.??
  • ????GetDocPropRange().Style?=?"Normal";??
  • }??
  • ?

    Working with Sheets

    ?

    [csharp]?view plaincopy
  • //?C#?列出所有Sheet??
  • private?void?ListSheets()??
  • {??
  • ????int?i?=?0;??
  • ???
  • ????Excel.Range?rng?=???
  • ????????ThisApplication.get_Range("Sheets",?Type.Missing);??
  • ????foreach?(Excel.Worksheet?sh?in?ThisWorkbook.Sheets)??
  • ????{??
  • ????????rng.get_Offset(i,?0).Value2?=?sh.Name;??
  • ????????i?=?i?+?1;??
  • ????}??
  • }??
  • ?

    ?

    ----------------------------------------------華麗分割-----------------------------------------------

    3. WorkSheet

    當你閱讀到這里的時候,你已經了解了大部分關于worksheet的概念。盡管Worksheet類提供了大量屬性,方法,事件;但其實它們的實現方法基本與Application和Workbook中的實現方法相同。這一節著重介紹之前沒有討論的內容。

    3.1?There is no Sheet Class..?

    什么?沒有Sheet類?

    ????? 我們知道,Workbook對象有一個屬性叫做Sheets,它是一個Workbook中Sheet的集合,但Excel中確實沒有叫做Sheet的類。取而代之的是,Sheets集合中的每一個元素都是一個WorkSheet對象或者Chart對象。你可以這樣去想: Worksheet以及Chart類都是specialized instances of an internal Sheet Class

    ?

    3.2? Working with Protection

    通常,protection特性用于防止用戶修改worksheet中的對象。一旦你使能了worksheet的protection功能,那么用戶將無法編輯&修改該sheet。在用戶界面,你可以選擇Tools | Protection | ProtectSheet(Excel2007下面是 審閱 | 更改 | 保護工作表)來使能protection。如下圖所示:

    ?

    你也可以定義允許用戶編輯的區域:

    通過以上兩個對話框,你就可以鎖定sheet,同時允許用戶編輯指定的選項以及區域(edit specificfeatures and ranges)。

    當然,上述的內容也可以讓C#幫我們完成。

    ?

    [csharp]?view plaincopy
  • //?C#??
  • WorksheetObject.Protect(Password,?DrawingObjects,?Contents,???
  • ??Scenarios,?UserInterfaceOnly,?AllowFormattingCells,???
  • ??AllowFormattingColumns,?AllowFormattingRows,???
  • ??AllowInsertingColumns,?AllowInsertingRows,???
  • ??AllowInsertingHyperlinks,?AllowDeletingColumns,???
  • ??AllowDeletingRows,?AllowSorting,?AllowFiltering,???
  • ??AllowUsingPivotTables);??
  • ?

    ?

    上面的Protect方法有很多參數,分別對應保護的內容。

    ?

    • Password??對應密碼,當你要撤銷保護時需要指定密碼
    • DrawingObjects????保護Shapes on the worksheet
    • Contents?????????保護cells,即所有單元格內容
    • Scenarios????????保護情景
    • UserInterfaceOnly????? 允許通過代碼修改,不允許通過用戶界面修改AllowFormattingCells AllowFormattingColumns….后面不再贅述

    ?

    下面這個例子,設置了密碼,同時只允許Sorting

    ?

    [csharp]?view plaincopy
  • //?C#??
  • ((Excel.Worksheet)ThisApplication.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);??
  • ?

    下面的代碼展示如何去保護(提示讓用戶輸入密碼)

    ?

    [csharp]?view plaincopy
  • //?C#??
  • ((Excel.Worksheet)ThisApplication.Sheets[1]).??
  • ??Unprotect(GetPasswordFromUser());??
  • ?

    除此之外,Protection還提供了AllowEditRanges屬性,可以讓你指定可編輯的范圍。AllowEditRanges屬性是AllowEditRange對象的集合,每一個對象都提供了一些有用的屬性,比如:

    ?

    • 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

    ?

    下面這個例子演示了Protection的功能,當你點擊Protect時,你只能編輯陰影區域,點擊Unprotect可以去保護。

    代碼如下:(對應點擊圖中的鏈接(Protect,Unprotect)執行的代碼)

    ?

    [csharp]?view plaincopy
  • //?C#??
  • ???
  • private?void?ProtectSheet()??
  • {???????
  • ????Excel.Worksheet?ws?=??
  • ??????(Excel.Worksheet)ThisApplication.ActiveSheet;??
  • ???
  • ????Excel.AllowEditRanges?ranges?=?ws.Protection.AllowEditRanges;??
  • ????ranges.Add("Information",???
  • ????????ThisApplication.get_Range("Information",?Type.Missing),???
  • ????????Type.Missing);??
  • ????ranges.Add("Date",???
  • ????????ThisApplication.get_Range("Date",?Type.Missing),?Type.Missing);??
  • ???
  • ????ws.Protect(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);??
  • }??
  • ???
  • private?void?UnprotectSheet()??
  • {??
  • ????Excel.Worksheet?ws?=???
  • ????????(Excel.Worksheet)?ThisApplication.Sheets["Worksheet?Class"];??
  • ????ws.Unprotect(Type.Missing);??
  • ???
  • ????//?Delete?all?protection?ranges,?just?to?clean?up.??
  • ????//?You?must?loop?through?this?using?the?index,???
  • ????//?backwards.?This?collection?doesn't?provide???
  • ????//?an?enumeration?method,?and?it?doesn't?handle??
  • ????//?being?resized?as?you're?looping?in?a?nice?way.??
  • ????Excel.AllowEditRanges?ranges?=?ws.Protection.AllowEditRanges;??
  • ????for?(int?i?=?ranges.Count;?i?>=?1;?i--)??
  • ????{??
  • ????????ranges[i].Delete();??
  • ????}??
  • }??
  • 3.3? Object Properties

    ?

    Worksheet類提供了一些屬性(that return objects),下面介紹兩個有用屬性:

    Comments以及Outline

    3.3.1 ?Comments (批注)

    在Excel2007中,選中一塊區域或者單元格后,點擊右鍵,可以插入批注。插入批注后的樣子如下圖所示

    Worksheet類提供Comments屬性,通過該屬性,你可以訪問該工作表內的所有批注。Comments類沒有多少屬性,你可能會使用Visible屬性來控制批注的顯示與隱藏,Delete屬性來刪除批注,或者你可能會發現Text方法比較有用,因為可以通過它來給批注增加內容或者重寫批注。

    下面是一個及其簡單的例子,來控制顯示批注

    ?

    [csharp]?view plaincopy
  • //?C#??
  • private?void?ShowOrHideComments(bool?show)??
  • {??
  • ????//?Show?or?hide?all?the?comments:??
  • ????Excel.Worksheet?ws?=???
  • ????????(Excel.Worksheet)?ThisApplication.Sheets["Worksheet?Class"];??
  • ???
  • ????for?(int?i?=?1;?i?<=?ws.Comments.Count;?i++)??
  • ????{??
  • ????????ws.Comments[i].Visible?=?show;??
  • ????}??
  • }??
  • 3.3.2 Outline

    ?

    Outline的功能是把row劃分成組,使得Excel的顯示更有層次感與結構氣息。

    例如,下面兩張圖片

    左圖:創建Outline??????????????????????????? 右圖:折疊后效果

    tline屬性本身是一個Outline對象,它自身屬性不多,主要有以下幾個:

    ?

    • l? AutomaticStyles???????? 告訴Excel是否應用automatic style to outline
    • l? SummaryColumn?????? get or set the location of the summarycolumns, (兩個選項:? xlSummaryOnLeft? xlSummaryOnRight)
    • l? SummaryRow??????????? get or set the location of thesummary rows,(兩個選項:? xlSummaryAbove? xlSummaryBelow)
    • l? ShowLevels??????????????? 允許你折疊/擴展outline groups to the row level and/or column levelyou want.

    ?

    經過上面的介紹,你應該對Outline有了基本的了解,下面開始使用C#操作Outline。

    首先是創建Group,創建Group是簡單的,你可以調用range對象的Group()方法;調用Ungroup()方法移除Group。

    ?

    [csharp]?view plaincopy
  • //?C#??
  • private?void?WorkWithGroups()??
  • {??
  • ????Excel.Worksheet?ws?=???
  • ????????(Excel.Worksheet)?ThisApplication.ActiveSheet;??
  • ???
  • ????//?Set?worksheet-level?features?for?the?outline.??
  • ????//?In?this?case,?summary?rows?are?below??
  • ????//?the?data?rows?(so?Excel?knows?where?to?put??
  • ????//?the?summary?rows),?and?we?don't?want?Excel??
  • ????//?to?format?the?summary?rows--that's?already?been?done.??
  • ????ws.Outline.SummaryRow?=?Excel.XlSummaryRow.xlSummaryBelow;??
  • ????ws.Outline.AutomaticStyles?=?false;??
  • ???
  • ????//?Group?the?two?named?ranges.?Each?of?these??
  • ????//?ranges?extends?across?entire?rows.??
  • ????ThisApplication.get_Range("Data2001",?Type.Missing).??
  • ????????Group(Type.Missing,?Type.Missing,?Type.Missing,?Type.Missing);??
  • ????ThisApplication.get_Range("Data2002",?Type.Missing).??
  • ????????Group(Type.Missing,?Type.Missing,?Type.Missing,?Type.Missing);??
  • ????ThisApplication.get_Range("AllData",?Type.Missing).??
  • ????????Group(Type.Missing,?Type.Missing,?Type.Missing,?Type.Missing);??
  • ???
  • ????//?The?range?of?rows?from?24?to?27?doesn't?have???
  • ????//?a?named?range,?so?you?can?work?with?that???
  • ????//?range?directly.??
  • ????Excel.Range?rng?=?(Excel.Range)ws.Rows["24:27",?Type.Missing];??
  • ????rng.Group(Type.Missing,?Type.Missing,?Type.Missing,???
  • ????Type.Missing);??
  • ???
  • ????//?Collapse?to?the?second?group?level.??
  • ????ws.Outline.ShowLevels(2,?Type.Missing);??
  • }??
  • ?

    對于unnamed range,方法如下:

    ?

    [csharp]?view plaincopy
  • //?C#??
  • Excel.Range?rng?=?(Excel.Range)ws.Rows["24:27",?Type.Missing];??
  • rng.Group(Type.Missing,?Type.Missing,???
  • ???????????Type.Missing,?Type.Missing);??
  • ?

    在前面的圖片中點擊Clear Groups link將清除Groups,對應代碼如下:

    ?

    [csharp]?view plaincopy
  • //?C#??
  • private?void?ClearGroups()??
  • {??
  • ????Excel.Worksheet?ws?=???
  • ????????(Excel.Worksheet)?ThisWorkbook.Sheets["Worksheet?Class"];??
  • ???
  • ????//?Specify?RowLevels?and/or?ColumnLevels?parameters:??
  • ????ws.Outline.ShowLevels(3,?Type.Missing);??
  • ???
  • ????Excel.Range?rng?=?(Excel.Range)?ws.Rows["24:27",?Type.Missing];??
  • ????rng.Ungroup();??
  • ???
  • ????ThisApplication.get_Range("Data2001",?Type.Missing).Ungroup();??
  • ????ThisApplication.get_Range("Data2002",?Type.Missing).Ungroup();??
  • ????ThisApplication.get_Range("AllData",?Type.Missing).Ungroup();??
  • }??
  • ?

    OK,通過上面的技巧,你就可以創建&移除groups了。同時你也可以控制工作表上顯示的group的層次了!

    ?

    ----------------------------------------------華麗分割-----------------------------------------------

    ?

    4. Range

    Range 對象將是你在開發關于Excel的應用程序中最經常使用的,在你操作任何Excel中的區域之前,你都要使用一個Range對象來表示該區域,然后通過Range對象的方法和屬性來操作該區域。

    Range對象是如此的重要,以至于本文上述所有的例子幾乎都存在Range對象。通常,一個Range對象可以代表一個單元格,一行,一列,一塊區域(containing oneor more blocks of cells)甚至是一組在不同sheets中的單元格。

    不幸的是,由于Range對象太大,成員太多,故不可能對其成員進行逐一描述。所以,下面從三個比較重要的方面介紹Range對象

    ?

    • l? 在代碼中引用ranges
    • l? 在代碼中操作ranges
    • l? 使用Range對象完成特定任務
    4.1Managing The Selection

    ?

    ????? Work with current selection 等價于修改當前選中Range的屬性和行為,不過你最好避免這么做。因為 ,selection within Excel代表著用戶的選擇。如果你修改了它,那么將導致用戶失去對“當前選擇”的控制。關于selection,第一準則是:you should call the Selectmethod only if your intent is to change the user’s selection.

    例如,下面的代碼將清除用戶當前選中單元格旁邊的單元格的內容

    ?

    [csharp]?view plaincopy
  • //?C#??
  • ThisApplication.ActiveCell.CurrentRegion.Select();??
  • ((Excel.Range)ThisApplication.Selection).ClearContents();??
  • ?

    ?

    4.2? Referring to a Range in Code

    1)????基本的引用Range方法

    1.???引用ActiveCell

    ?

    [csharp]?view plaincopy
  • rng?=?ThisApplication.ActiveCell;??
  • ?

    2.???使用get_Range方法,指定Range范圍

    ?

    [csharp]?view plaincopy
  • //?C#??
  • rng?=?ws.get_Range("A1",?Type.Missing);??
  • rng?=?ws.get_Range("A1:B12",?Type.Missing);??
  • ?

    3.???使用Cells屬性

    ?

    [csharp]?view plaincopy
  • //?C#??
  • rng?=?(Excel.Range)ws.Cells[1,?1];??
  • ?

    4.???指定Range的角,同時可以直接引用該Range的Cells Rows Columns屬性

    ?

    [csharp]?view plaincopy
  • //?C#??
  • 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;??
  • ?

    5.???引用一個帶名字的Range

    ?

    [csharp]?view plaincopy
  • //?C#??
  • rng?=?ThisApplication.Range("SomeRangeName",?Type.Missing);??
  • ?

    6.???引用特定的行或者列

    ?

    [csharp]?view plaincopy
  • //?C#??
  • 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];??
  • ?

    7.???使用Application對象的Selection方法獲取選中Cells對應的Range

    執行下面代碼,將在調試窗口看到:"$C$3"

    ?

    [csharp]?view plaincopy
  • //?C#??
  • System.Diagnostics.Debug.WriteLine(??
  • ????((Excel.Range)ThisApplication.Selection).??
  • ????get_Address(??Type.Missing,?Type.Missing,???
  • ????????????????????????Excel.XlReferenceStyle.xlA1,???
  • ?????????????????Type.Missing,?Type.Missing)??
  • );??
  • ???
  • ?

    8.???兩個Range合并為一個Range

    ?

    [csharp]?view plaincopy
  • //?簡單的合并方法??
  • rng?=?ThisApplication.get_Range("A1:D4,?F2:G5",?Type.Missing);??
  • ???
  • //?相對復雜的合并方法??
  • rng1?=?ThisApplication.get_Range("A1",?"D4");??
  • rng2?=?ThisApplication.get_Range("F2",?"G5");??
  • //?Note?that?the?Union?method?requires?you?to?supply?thirty??
  • //?parameters:???
  • rng?=?ThisApplication.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);??
  • ?

    9.???Range的Offset屬性

    ?

    [csharp]?view plaincopy
  • //?adds?content?to?the?area?under?the?cell?at?row?1,?column?1??
  • rng?=?(Excel.Range)?ws.Cells[1,?1];??
  • for?(int?i?=?1;?i?<=?5;?i++)??
  • {??
  • ????rng.get_Offset(i,?0).Value2?=?i.ToString();//參數1代表Row,2代表Col??
  • }??
  • ?

    ?

    10,11,12....100#$%^&**(&%$...太多了,不能一一介紹

    經過上面的介紹,是不是有一點暈呢?下面通過一個小例子來演示一下Range的功能吧。

    ??????在使用Excel中,我們可能希望在選中一個單元格后使整行加粗顯示,即實現選中效果,但是Excel中沒有對該功能的支持。但是,通過代碼不難實現該功能,首先看一下實際效果吧。

    可以看到,選中的單元格所在行變成了Bold顯示。

    其實現代碼如下:

    ?

    [csharp]?view plaincopy
  • //?C#??
  • private?int?LastBoldedRow?=?0;??
  • private?void?BoldCurrentRow(Excel.Worksheet?ws)???
  • {??
  • ????//?Keep?track?of?the?previously?bolded?row.??
  • ???
  • ????//?Work?with?the?current?active?cell.??
  • ????Excel.Range?rngCell?=?ThisApplication.ActiveCell;??
  • ???
  • ????//?Bold?the?current?row.??
  • ????rngCell.EntireRow.Font.Bold?=?true;??
  • ???
  • ????//?Make?sure?intRow?isn't?0?(meaning?that???
  • ????//?this?is?your?first?pass?through?here).??
  • ????if?(LastBoldedRow?!=?0)???
  • ????{??
  • ????????//?If?you're?on?a?different??
  • ????????//?row?than?the?last?time?through?here,??
  • ????????//?make?the?old?row?not?bold.??
  • ????????if?(rngCell.Row?!=?LastBoldedRow)???
  • ????????{??
  • ????????????Excel.Range?rng?=???
  • ????????????????(Excel.Range)ws.Rows[LastBoldedRow,?Type.Missing];??
  • ????????????rng.Font.Bold?=?false;??
  • ????????}??
  • ????}??
  • ????//?Store?away?the?new?row?number???
  • ????//?for?next?time.??
  • ????LastBoldedRow?=?rngCell.Row;??
  • }??
  • 例子中的workbook通過SheetSelectionChange事件監聽器調用BoldCurrentRow方法。

    ?

    下面的代碼verifies that the new selection is within the correct range using the?Intersect?method ofthe?Application?object

    ?

    [csharp]?view plaincopy
  • //?C#??
  • protected?void?ThisWorkbook_SheetSelectionChange(??
  • ??System.Object?sh,?Excel.Range?Target)??
  • {??
  • ????//?Don't?forget?that?the?Intersect?method?requires??
  • ????//?thirty?parameters.??
  • ????if?(ThisApplication.Intersect(Target,???
  • ????????ThisApplication.get_Range("BoldSelectedRow",?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)???
  • ????????!=?null)??
  • ????{??
  • ????????//?The?selection?is?within?the?range?where?you're?making??
  • ????????//the?selected?row?bold.??
  • ????????BoldCurrentRow((Excel.Worksheet)?sh);??
  • ????}??
  • }??
  • 4.3? Working with Ranges

    ?

    ????? 一旦你獲得了一個Range的引用,你能做什么呢?答案是: Endless,as you can imagine。下面介紹兩個典型的場景。

    4.3.1 Autimatically Filling Ranges

    自動填充功能?? (AutoFill方法用于向一個范圍中填充遞增或者遞減的值)

    首先看一下: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
  • //?實現圖示自動填充的C#代碼??
  • private?void?AutoFill()??
  • {??
  • ????Excel.Range?rng?=?ThisApplication.get_Range("B1",?Type.Missing);??
  • ????rng.AutoFill(ThisApplication.get_Range("B1:B5",?Type.Missing),???
  • ????????Excel.XlAutoFillType.xlFillDays);??
  • ???
  • ????rng?=?ThisApplication.get_Range("C1",?Type.Missing);??
  • ????rng.AutoFill(ThisApplication.get_Range("C1:C5",?Type.Missing),???
  • ????????Excel.XlAutoFillType.xlFillMonths);??
  • ???
  • ????rng?=?ThisApplication.get_Range("D1",?Type.Missing);??
  • ????rng.AutoFill(ThisApplication.get_Range("D1:D5",?Type.Missing),???
  • ????????Excel.XlAutoFillType.xlFillYears);??
  • ???
  • ????rng?=?ThisApplication.get_Range("E1:E2",?Type.Missing);??
  • ????rng.AutoFill(ThisApplication.get_Range("E1:E5",?Type.Missing),???
  • ????????Excel.XlAutoFillType.xlFillSeries);??
  • ?

    ?

    4.3.2 Searching Within Ranges

    Range類的Find方法允許你在Range中進行搜索。當然你也可以再Excel界面中使用Ctrl+F打開搜索對話框,如下圖所示

    下表列出了Range.Find方法的參數

    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.

    下面還是通過一個例子來學習Range.Find的用法。首先貼圖:

    ?

    不難看出,我們要搜索apples。下面是其實現的代碼:

    ?

    [csharp]?view plaincopy
  • //?C#??
  • private?void?DemoFind()??
  • {??
  • ????//得到range對象??
  • ????Excel.Range?rng?=?ThisApplication.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);??
  • ????}??
  • }??
  • ?

    若要取消查找后的顯示效果:

    [csharp]?view plaincopy
  • //?取消查找結構的顯示??
  • private?void?ResetFind()??
  • {??
  • ????Excel.Range?rng?=?ThisApplication.??
  • ????????get_Range("Fruits",?Type.Missing);??
  • ???
  • ????rng.Font.Color?=?ColorTranslator.ToOle(Color.Black);??
  • ????rng.Font.Bold?=?false;??
  • }??
  • ?

    -----------------------------------------華麗分割-----------------------------------

    OK,終于寫完了。本文主要介紹了Excel的幾大對象,主要介紹的是一些API。后面將會通過實例,結合 VS2010,用C#來實現對Excel的操作。感謝閱讀。

    ?

    -------------------------------------------------------------------------------------

    本文的PDF版本下載:點此下載

    轉載于:https://www.cnblogs.com/gc2013/p/3934957.html

    總結

    以上是生活随笔為你收集整理的C#操作Excel(1)Excel对象模型的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。