Excel Programming in VSTO (book:Visual Studio Tools for Office 2007 VSTO) Note

The Office PIAs (Primary Interop Assemblies) allow .NET code to call the unmanaged object models that Office applications expose.

 

Programming Excel:

                -Thebasic hierarchy of the Excel object model

                

 

Working with Excel Events

                -...

Working with Excel Objects

                -Application Object

                                -1.ControllingExcel’s Screen Updating Behavior

                                                -**Repainting the screen after each operation can be quite costly.

                                                -**Besure to set this property back to true when your code is finished. a try catch-block is a handy way to ensure that the property is reset even if an exceptionis thrown.

                                                -SampleCode:

                                               

 boololdScreenUpdatingSetting = this.Application.ScreenUpdating;
            try
            {
               this.Application.ScreenUpdating = false;
                //DOSOMETHING
            }
            finally
            {
               this.Application.ScreenUpdating = oldScreenUpdatingSetting;
            }

                                -2.Changingthe Mouse Pointer (when the operation is busy)

                                                -SampleCode:

                                              

  Excel.XlMousePointerorginalCursor = this.Application.Cursor;
            try
            {
               this.Application.Cursor = Excel.XlMousePointer.xlWait;
                //DOSOMETHING
            }
            finally
            {
               this.Application.Cursor = orginalCursor;
            }

                                -3.Displayinga Message in Excel’s Status Bar

                                                -SampleCode:

                                               

 objectoldValue = this.Application.StatusBar;
            try
            {
                //DOSOMETHING
                this.Application.StatusBar = "10% iscompleted";
            }
            finally
            {
               this.Application.StatusBar = oldValue;
            }

                                -4.Controllingthe Calculation of Workbooks

                                                -XlCalculation

                                                -**(SetCalculation to xlCalculationManual)Using manual calculation may be another wayto speed up your code if you are updating a large number of cells that arereferred to by formulas.

                                                -UsingBuilt-In Excel Functions in Your Code

                                                                -SampleCode:

                                                               

 Excel.WorksheetFunctionfunc = this.Application.WorksheetFunction;
 
                                                                doubleresult = func.Acos(.1);
                                                                doubleresult2 = func.Atan2(.1, .2);
                                                                doubleresult3 = func.Atanh(.1);

                                -5.Undoin Excel

                                                -Exceldoes not support undoing actions taken by your code. As soon as your codetouches the object model, Excel clears the undo history and it does not add anyof the actions your code performs to the undo history

                                -6.Sending Keyboard Commands to Excel

                -WorkbooksCollection

                                -1.Iteratingover the Open Workbooks

                                                -SampleCode:

                                           

     Excel.Workbooksworkbooks = this.Application.Workbooks;
            foreach(Excel.Workbook workbook in workbooks)
            {
               MessageBox.Show(workbook.Name);
            }

                                -2.Accessinga Workbook in the Workbooks Collection

                                                -get_Item(index)

                                                -get_Item(name)

                -WorkbookObject

                -Workingwith the Worksheets, Charts, and Sheets Collections

                -Workingwith Document Properties

                                -1.Iteratingover the DocumentProperties Collection

                                                -SampleCode:

                                               

 Office.DocumentPropertiescustomProps = this.Application.Workbooks[1].CustomDocumentProperties;
           Office.DocumentProperties builtinProps =this.Application.Workbooks[1].BuiltinDocumentProperties;
 
            foreach (Office.DocumentPropertycustomProp in customProps)
            {
                try
                {
                   MessageBox.Show(String.Format(
                       "{0}-{1}", customProp.Name, customProp.Value));
                }
                catch
                {
                   MessageBox.Show(String.Format(
                       "{0}", customProp.Name));
                }
            }
 
            foreach(Office.DocumentProperty builtinProp in builtinProps)
            {
                try
                {
                   MessageBox.Show(String.Format(
                       "{0}-{1}", builtinProp.Name, builtinProp.Value));
                }
                catch
                {
                    MessageBox.Show(String.Format(
                       "{0}", builtinProp.Name));
                }
            }

 

                                -2.Accessinga DocumentProperty in the DocumentProperties Collection

                                                -SampleCode:

                                               

 Office.DocumentPropertiesbuiltinProps = this.Application.Workbooks[1].BuiltinDocumentProperties;
 
           Office.DocumentProperty builtinProp = builtinProps["Author"];

                -WindowsCollections

                -WindowObject

                -NamesCollection and Name Object

                -WorksheetObject

                                -1.WorksheetManagement

                                                -Movemethod:move a worksheet to a different tab position

                                                -Copymethod:

                                                -Activatemethod:activate a particular worksheet

                                                -Deletemethod:

                                                -Visibleproperty:hide/show worksheet

                                                                -xlSheetVisible

                                                                -xlSheetHidden

                                                                -xlSheetVeryHidden:hidesthe worksheet so that it can only be shown again by setting the Visibleproperty to xlSheetVisible

                                                                -SampleCode:

                                                                this.Visible= Excel.XlSheetVisibility.xlSheetVeryHidden;

                                -2.Protectinga Worksheet

                -RangeObject

                                -TheRange object represents a range of cells in a spreadsheet. A range can containone cell, multiple contiguous cells, and even multiple noncontiguous cells.

                                -Gettinga Range Object for a Particular Cell or Range of Cells

                                                -Worksheet.get_RangeMethod

                                                                -A1-stylereferences

                                                                                -A1:cell at row 1, column A

                                                                                -$A$1:cellat row 1, column A

                                                                                -A1:B1:twocells at row 1, column A and row 1, column B.

                                                                                -A1,C1:twocells where the first cell is at row 1, column A and the second cell is at row4, column C.

                                                                -SampleCode:

                                                                Cells.get_Item(1,1)==this.get_Range["A1"]

                                                -Workingwith Addresses

                                                                -R1C1-stylereferences

                                                                                -e.g:R15C16

                                                -CreatingNew Ranges Using Operator Methods

                                                                -unionoperator

                                                                -intersectionoperator

                                                                -get_Offsetmethod

                                                -Workingwith Areas

                -Cells

                -Regions

                                -Editingthe Values in a Range

                                -Copying,Clearing, and Deleting Ranges

                                -FindingText in a Range

                                -Formattinga Range of Cells

                                                   

VSTO Data Programming

                -UsingBinding Sources as Proxies

                                -Thereason is because the control can bind to the proxy even if the data in thetable is not currently available.

                -Data-BindableControls

                                -simple-data-bindable:a control property is bound to a single data element,such as one column in a data table

-control: e.g.: namedrange

                                -complex-data-bindable:a control property is bound to more than one data element, such as multiple columns in a data table

-control: e.g: listobject

-Updating Data That Is Bound to Host Controls

                                -simpledata binding

                                                -changesin the data source are reflected automatically in the host control

                                                -changesin the host control require an explicit call to update the data source

                                                So...

                                                -Updatingthe In-Memory Data Source

                                                            

    -Solution1: Call the WriteValue method of the Binding object that binds the control tothe data source.
                                                                                -Code:
                                                                                                this.namedRange1.DataBindings["Value2"].WriteValue();
                                                                -Solution2:AutomaticallyUpdating the In-Memory Data Source
                                                                                -Code:
                                                                                                this.namedRange1.DataBindings["Value2"].DataSourceUpdateMode=
                                                                                                DataSourceUpdateMode.OnPropertyChanged;

                                -ComplexData Binding

                                                -Youdo not need to explicitly update the in-memory data source

                -CachingData in the Data Island

                                -CachingYour Own Data Types, data could be persisted into the document as XML

                                                -1.Thedata must be stored in a public member variable or property of a host item

                                                -2.propertymust have no parameters and be both readable and writable

                                                -3.Theruntime type of the data must be serializable

                                                -SampleCode:

                                                

[Cached]
                                                publicstring CustomName;
 
                                                privatevoid Sheet4_Startup(object sender, System.EventArgs e)
                                                {
                                                                if(this.NeedsFill("CustomName"))
                                                                {
                                                                                this.CustomName= "UnKnown Customer";
                                                                }
                                                               
                                                }

                                -DynamicallyAdding and Removing Cached Members from the Data Island

                                                -boolNeedsFill(string memberName)

                                                -boolIsCached(string memberName):tells you whether the item will be saved to thedata island when the user saves the document

                                                -voidStartCaching(string memberName):dynamically add a members from the set ofmembers that will be saved to the data island

                                                -voidStopCaching(string memberName):dynamically remove a members from the set ofmembers that will be saved to the data island

Server Data Scenarios

                                -Accessingthe Data Island

                                                -ServerDocument:canread and write the data island directly; it does not need to start up Word orExcel on the server

                                               

Data Island

                -why need Data Island?

                                -sepeatedocument schema and document data -via server document

                                -supportoffline mode-via server document

                                -updatedata without open excel or word

                -Cache(XML)

                                -CacheType: Dataset, DataTable, Custom Cache Data Type

                                -CustomCache Data Type

                                                -implement:ICachedType

                                                -XMLserializable

                                                -nullvalue object cannot be cached, must initilize first

                -ServerDocument

                                -Microsoft.VisualStudio.Tools.Application.Runtime

                                -Method:

                                                -ServerDocument.RemoveCustomization(stringdocument path)

                                                -ServerDocument.AddCustomization(stringdocument path...)

                                                -ServerDocument.IsCustmized(stringdocument path)

                                                -ServerDocument.IsCacheEnable(stringdocument path)

                                -Canaccess any property with [Cached()]

                                                -SampleCode:

                                               

                                                                //ReadCached Data
                                                                ServerDocumentds=new ServerDocument(string document path);
                                                                stringstrXML=ds.CachedData.HostItems("XXXNamespace.Sheet1").CachedData["cahceddatasetname"].XML;
                                                                System.IO.StringReaderreader=new System.IO.StringReader(strXML);
                                                                northwindDataset.ReadXML(reader);
                                                                northwindDataset.AcceptChanges();
                                                               
                                                                //UpdateCached Data
                                                                -Way1
                                                                System.IO.Writer

                                          

                               

               

               

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值