Understanding the Excel Object Model from a. Net developer's Perspective


Figure 6. With the PrecisionAsDisplayed property set to True, Excel uses only the visible decimals to perform its calculations



Yüklə 0,58 Mb.
səhifə4/7
tarix18.08.2018
ölçüsü0,58 Mb.
#72354
1   2   3   4   5   6   7

Figure 6. With the PrecisionAsDisplayed property set to True, Excel uses only the visible decimals to perform its calculations.

  • ReadOnly (Boolean, read-only): Returns True if the workbook was opened as read-only. You may want to take different actions in your application if you're unable to save data to the workbook.

  • Saved (Boolean): Gets or sets the saved state of the workbook. If the user has made modifications to the workbook's contents or structure, the Saved property is True. Attempting to close the workbook or quit Excel will cause an alert to appear, prompting you to save the workbook (unless you've set the Application.DisplayAlerts property to False). If you set the Saved property value to False in your code, Excel will treat your workbook as if it had already been saved, and not prompt you to save it again.

Working with Document Properties

Just like the other Office applications, Excel allows you to store document properties along with the workbook. Excel provides a number of built-in properties, and you can add your own, as well. Selecting File|Properties displays the dialog box shown in Figure 7, and you can also select the Custom tab to create and modify custom properties.





Figure 7. Use this dialog box to set document properties.

Use the Workbook class BuiltInDocumentProperties property to work with built-in properties, and the CustomDocumentProperties property to work with custom properties. Each of these properties returns a DocumentProperties object, which is a collection of DocumentProperty objects. You can use the Item property of the collection to retrieve a particular property, either by name, or by index within the collection. The full list of property names is available in the Excel documentation, but there's an easy way to retrieve the list: the following procedure runs when you click the Document Properties link on the sample workbook (see Figure 8). This procedure calls the DumpPropertyCollection method to list all the built-in properties and their current values, and then repeats the process for the custom properties. In addition, the procedure modifies the Revision Number property individually, and creates a new custom property:

' Visual Basic

Private Sub DisplayDocumentProperties()

Dim prp As Office.DocumentProperty

Dim prps As Office.DocumentProperties

Dim rng As Excel.Range = _

ThisApplication.Range("DocumentProperties")

Dim i As Integer

Try


ThisApplication.ScreenUpdating = False

Try


prps = DirectCast( _

ThisWorkbook.BuiltinDocumentProperties, _

Office.DocumentProperties)

' Set the Revision Number property:

prp = prps.Item("Revision Number")

prp.Value = CType(prp.Value, Integer) + 1

' Dump contents of the collection:

DumpPropertyCollection(prps, rng, i)

Catch ex As Exception

MessageBox.Show(ex.Message)

End Try

' Work with custom properties:



Try

prps = DirectCast( _

ThisWorkbook.CustomDocumentProperties, _

Office.DocumentProperties)

DumpPropertyCollection(prps, rng, i)

Catch ex As Exception

MessageBox.Show(ex.Message)

End Try


' Add a custom property:

Try


' Delete the property, if it exists.

prp = prps.Item("Project Name")

prp.Delete()

Catch


' Do nothing if you get an exception.

End Try


Try

' Add a new property.

prp = prps.Add("Project Name", False, _

Office.MsoDocProperties.msoPropertyTypeString, _

"White Papers")

Catch ex As Exception

MessageBox.Show(ex.Message)

End Try


Finally

ThisApplication.ScreenUpdating = True

End Try

End Sub


Private Sub DumpPropertyCollection( _

ByVal prps As Office.DocumentProperties, _

ByVal rng As Excel.Range, ByRef i As Integer)

Dim prp As Office.DocumentProperty

For Each prp In prps

rng.Offset(i, 0).Value = prp.Name

Try

If Not prp.Value Is Nothing Then



rng.Offset(i, 1).Value = _

prp.Value.ToString

End If

Catch


' Do nothing at all.

End Try


i += 1

Next


End Sub

// C#


private void DisplayDocumentProperties()

{

Office.DocumentProperty prp = null;



Office.DocumentProperties prps =

(Office.DocumentProperties)

ThisWorkbook.BuiltinDocumentProperties;

Excel.Range rng = ThisApplication.

get_Range("DocumentProperties", Type.Missing);

int i = 0;

try

{

ThisApplication.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, ThisApplication.Name);

}

// Work with custom properties:



try

{

prps = (Office.DocumentProperties)



ThisWorkbook.CustomDocumentProperties;

DumpPropertyCollection(prps, rng, i);

}

catch (Exception ex)



{

MessageBox.Show(ex.Message, ThisApplication.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, ThisApplication.Name);

}

}

finally



{

ThisApplication.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;

}

Tip   The previous code sample, DisplayDocumentProperties, used several enumerations and types from the Microsoft.Office.Core assembly. The sample code includes an Imports/using statement that sets up the text "Office" as an abbreviation for this namespace, just as it does for the "Excel" abbreviation. The project template automatically sets up the "Excel" abbreviation. You'll need to add the "Office" statement yourself.



Figure 8. Built-in document properties

Note   Although you're working with Excel and its objects here, it's Office that supplies the list of available built-in document properties, and Excel doesn't necessarily implement all the properties—attempting to access the Value property for undefined properties triggers an exception. The sample procedure includes simple exception handling to deal with this situation, should it occur.

Working with Styles

Much like a Word document, Excel workbooks allow you to apply named styles to regions within the workbook, and Excel supplies a number of predefined (although not terribly interesting) styles. You can use the Format|Styles menu item to display a dialog box that allows you to interactively modify styles, as shown in Figure 9.



Figure 9. Modify styles interactively with this dialog box.

If you click Modify on the Style dialog box, you'll display the Format Cells dialog box shown in Figure 10.





Figure 10. Use the Format Cells dialog box to modify styles.

The Format Cells dialog box displays all the options you can use when formatting cells, and each of the options available in this dialog box is available from within your code. You can use the Styles property of a Workbook object to interact with and apply styles to ranges within the workbook.

You can create, delete, and modify styles, using the Styles property of a Workbook object. Clicking Apply Style on the sample workbook runs the following procedure, which creates a new style (or uses an existing one, if you've run the code already), sets up the various aspects of the style, and applies it to a region:

' Visual Basic

Private Sub ApplyStyle()

Const STYLE_NAME As String = "PropertyBorder"

Dim rng As Excel.Range

' Get the range containing all the document properties.

rng = GetDocPropRange()

Dim sty As Excel.Style

Try

sty = ThisWorkbook.Styles(STYLE_NAME)



Catch

sty = ThisWorkbook.Styles.Add(STYLE_NAME)

End Try

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 = XlPattern.xlPatternSolid

rng.Style = STYLE_NAME

rng.Columns.AutoFit()

End Sub

// C#


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();

}

The GetDocPropRange method returns the range filled in by the document properties. This procedure uses the Range.End method to find the end of the range filled with document properties, and then creates a new range based on the upper-left corner of the range and the bottom-right corner:



' Visual Basic

Private Function GetDocPropRange() As Excel.Range

Dim rng As Excel.Range = _

ThisApplication.Range("DocumentProperties")

Dim rngStart As Excel.Range = _

DirectCast(rng.Cells(1, 1), Excel.Range)

Dim rngEnd As Excel.Range = _

rng.End(Excel.XlDirection.xlDown).Offset(0, 1)

Return ThisApplication.Range(rngStart, rngEnd)

End Function

// C#

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);

}

Tip   For more information on retrieving and working with Range objects, see the section titled "Working with Ranges" later in this document.

Once you've run the code, the region containing document properties on the sample workbook changes shading and font, as shown in Figure 11.





Figure 11. After applying a custom style

Clicking Clear Style runs the following procedure, which clears the style for the same region:

' Visual Basic

Private Sub ClearStyle()

' Get the range containing all the document properties, and

' clear the style.

GetDocPropRange().Style = "Normal"

End Sub


// C#

private void ClearStyle()

{

// Get the range containing all the document properties, and



// clear the style.

GetDocPropRange().Style = "Normal";

}

Working with Sheets



The Workbook class provides a Sheets property that returns a Sheets object. This object contains a collection of Sheet objects, each of which can be either a Worksheet or a Chart object. Clicking List Sheets on the sample workbook runs the following procedure and lists all the existing sheets in the workbook:

' Visual Basic

Private Sub ListSheets()

Dim sh As Excel.Worksheet

Dim rng As Excel.Range

Dim i As Integer

rng = ThisApplication.Range("Sheets")

For Each sh In ThisWorkbook.Sheets

rng.Offset(i, 0).Value = sh.Name

i = i + 1

Next sh

End Sub


// C#

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;

}

}



You may also find the following members of the Sheets class to be useful.

  • The Visible property allows you to show or hide an existing sheet without having to delete and recreate the sheet. Set the Visibility property to one of the XlSheetVisibility enumerated values (XlSheetHidden, XlSheetVeryHidden, xlSheetVisible). Using XlSheetHidden allows users to unhide the sheet through the Excel interface; using XlSheetVeryHidden requires that you run code to unhide the sheet:

  • ' Visual Basic

  • DirectCast(ThisWorkbook.Sheets(1), Excel.Worksheet).Visible = _

  • Excel.XlSheetVisibility.xlSheetVeryHidden



  • // C#

  • ((Excel.Worksheet) ThisWorkbook.Sheets[1]).Visible =

  • Excel.XlSheetVisibility.xlSheetVeryHidden;

  • The Add method allows you to add a new sheet to the collection of sheets in the workbook, and accepts four optional parameters indicating the location of the sheet, the number of sheets to add, and the type of sheet (worksheet, chart, and so on):

  • ' Visual Basic

  • Dim sh As Excel.Sheet = ThisWorkbook.Sheets.Add()



  • // C#

  • Excel.Sheet sh = ThisWorkbook.Sheets.Add(

  • Type.Missing, Type.Missing, Type.Missing, Type.Missing);

  • The Copy method creates a copy of a sheet, and inserts the sheet at the location you specify. You can specify to insert the new sheet either before or after an existing sheet, if you like. If you don't specify, Excel creates a new workbook to contain the new sheet. The following fragment copies the first sheet in the current workbook and places the copy after the third sheet:

  • ' Visual Basic

  • DirectCast(ThisWorkbook.Sheets(1), Excel.Worksheet). _

  • Copy(After:=ThisWorkbook.Sheets((3)))



  • // C#

  • ((Excel.Worksheet) ThisWorkbook.Sheets[1]).

  • Copy(Type.Missing, ThisWorkbook.Sheets[3]);.

  • The Delete method deletes a specified sheet:

  • ' Visual Basic

  • DirectCast(ThisWorkbook.Sheets(1), Excel.Worksheet).Delete



  • // C#

  • ((Excel.Worksheet) ThisWorkbook.Sheets[1]).Delete();

  • The FillAcrossSheets method copies data from a range on one sheet to all the other sheets within the workbook. You specify a range, and whether you want to copy data, formatting, or all, Excel does the rest. The following fragment copies data and formatting from a range named Data on one sheet to the same region on all the sheets in the workbook:

  • ' Visual Basic

  • ThisWorkbook.Sheets.FillAcrossSheets( _

  • ThisApplication.Range("Data"), Excel.XlFillWith.xlFillWithAll)



  • // C#

  • ThisWorkbook.Sheets.FillAcrossSheets(

  • ThisApplication.get_Range("Data", Type.Missing),

  • Excel.XlFillWith.xlFillWithAll);

  • The Move method works much like the Copy method, except that you end up with only one instance of the sheet. You can specify either the sheet to place your sheet before, or the sheet to place it after (but not both). Again, if you don't specify a location for the moved sheet, Excel creates a new workbook to contain it. The following fragment moves the first worksheet so that it's last:

  • ' Visual Basic

  • Dim shts As Excel.Sheets = ThisWorkbook.Sheets

  • DirectCast(shts(1), Excel.Worksheet).Move(After:=shts(shts.Count))



  • // C#

  • Excel.Sheets shts = ThisWorkbook.Sheets;

  • ((Excel.Worksheet)shts[1]).Move(Type.Missing, shts[shts.Count]);

Tip   If you have some reason to want to sort the list of sheets in a workbook, you can make use of the Move method to perform an inefficient bubble sort. Of course, because you're unlikely to have very many sheets, the speed of the sort won't be an issue.

  • The PrintOut method allows you to print the selected object (this method applies to several different objects). You can specify a number of optional parameters, including the pages to print (from and to), the number of copies, whether you want to preview before printing, the name of the printer to use, whether you want to print to a file, whether you want to collate, and the name of the file you want to print to. The following example prints the specified sheet, printing only the first page, requests two copies, and previews the document before printing, using the default printer:

  • ' Visual Basic

  • DirectCast(ThisWorkbook.Sheets(1), Excel.Worksheet). _

  • PrintOut(From:=1, To:=1, Copies:=2, Preview:=True)



  • // C#

  • ((Excel.Worksheet)ThisApplication.Sheets[1]).

  • PrintOut(1, 1, 2, true, Type.Missing, Type.Missing,

  • Type.Missing, Type.Missing);

  • The PrintPreview method allows you to display the specified object in the PrintPreview window, optionally disallowing changes to the page layout:

  • ' Visual Basic

  • DirectCast(ThisWorkbook.Sheets(1), Excel.Worksheet). _

  • PrintPreview(False)



  • // C#

  • ((Excel.Worksheet)ThisApplication.Sheets[1]).PrintPreview(false);

  • The Select method selects the specified object, moving the user's selection. (Use the Activate method instead to bring focus to the object without changing the user's selection.) You can optionally supply a reference to an object to be replaced by the current selection. The following fragment selects the first worksheet:

  • ' Visual Basic

  • ActiveWorkbook.Sheets(1).Select()



  • // C#

  • ((Excel.Worksheet)ThisApplication.Sheets[1]).Select(Type.Missing);

Tip   Many of the methods listed in this section apply to other classes. For example, the PrintOut method is provided by the Chart, Charts, Range, Sheets, Window, Workbook, Worksheet, and Worksheets classes. The methods work the same in each case; they just act on a different object. The Select method applies to just about every selectable object (and there are many of them).

Methods of the Workbook Class



The Workbook class provides a huge number of methods, many handling very specific situations. Rather than focus on the details, this section discusses some of the methods you're likely to use in every application, leaving the esoteric methods for later study. The following list describes some of the methods you're most likely to need:

  • The Activate method activates a workbook, selecting the first sheet in the workbook:

  • ' Visual Basic

  • ThisApplication.Workbooks(1).Activate



  • // C#

  • ThisApplication.Workbooks[1].Activate;

  • The Close method closes the specified workbook, optionally specifying whether changes should be saved. If the workbook has never been saved, you can specify a file name. In addition, if the workbook is to be routed to other users, you can specify whether you want to send the workbook on to the next user. The following fragment closes the workbook, discarding changes:

  • ' Visual Basic

  • ThisApplication.Workbooks(1).Close(SaveChanges:=False)



  • // C#

  • ThisApplication.Workbooks(1).Close(false,

  • Type.Missing, Type.Missing);

  • The Protect and Unprotect methods allow you to protect a workbook so that you can't add or delete worksheets, and to unprotect the workbook again. You can optionally specify a password, and can optionally indicate whether you want the structure protected (so users can't move sheets around) and whether you want the workbook's windows protected. Protecting a workbook does not keep a user from editing cells. To protect data, you must protect the worksheets. Call the Unprotect method, passing a password if it's required, to unprotect the workbook. The following example assumes a procedure named GetPasswordFromUser, which requests the user to enter a password, and returns the entered value:

  • ' Visual Basic

  • ThisApplication.Workbooks(1).Protect(GetPasswordFromUser())



  • // C#

  • ThisApplication.Workbooks[1].Protect(

  • GetPasswordFromUser(), Type.Missing, Type.Missing);

  • The Save method saves the workbook, as you might have expected. If you've never saved the workbook, you should call the SaveAs method instead, so you can specify a path (if you haven't yet saved the workbook, Excel saves it in the current folder with the name it was given when it was created):

  • ' Visual Basic

  • ' Save all open workbooks.

  • Dim wb As Excel.Workbook

  • For Each wb in ThisApplication.Workbooks

  • wb.Save

  • Next wb



  • // C#

  • // Save all open workbooks.

  • foreach (Excel.Workbook wb in ThisApplication.Workbooks)

  • {

  • wb.Save();

  • }

  • The SaveAs method is far more complex than the Save method. This method allows you to save the specified workbook, optionally specifying a name, a file format, a password, an access mode, and more. See the online help for a list of all the options. The following fragment saves the current workbook to a specified location, saving in XML format:

  • ' Visual Basic

  • ThisApplication.ActiveWorkbook.SaveAs("C:\MyWorkbook.xml", _

  • FileFormat:=Excel.XlFileFormat.xlXMLSpreadsheet)



  • // C#

  • ThisApplication.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);

Yüklə 0,58 Mb.

Dostları ilə paylaş:
1   2   3   4   5   6   7




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©muhaz.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin