Visual Studio Tools for Office: Using C# with Excel, Word, Outlook, and InfoPath【16】

Use the worksheet objects
Worksheet object represents a workbook in Excel worksheets. Worksheet has a Name property returns the name of the worksheet (for example, "Sheet1").

Worksheet Management
Worksheet object has a property Index, tabbed worksheet tab it shows the lower left corner of the worksheet window-based worksheet tab 1 position. You can use the Move method to move the worksheet to a different tab position. Move method has two optional parameters: Before a parameter, you can pass before you want to move a worksheet worksheet, and After a parameter, you can pass the worksheet to be moved after the worksheet. If two optional argument is omitted, Excel will create a new workbook and worksheet to a new workbook.

You can also make a copy of the worksheet using the replication method. Like the Move method, it requires two optional parameters: Before and After a parameter that specifies the copied sheet should be relative to the other sheets. You can specify the Before or After, but can not specify both parameters at the same time. If two optional argument is omitted, Excel will create a new workbook and copy the worksheet to a new workbook.

To activate a specific worksheet, use the Activate method. This method provided by the first window associated with the worksheet is the active window to activate the worksheet. It also selects the corresponding worksheet tab and display the worksheet in the active window.

Right-click the equivalent of the Sheet tab, and select "Delete" from the pop-up menu provided by the Delete method. When using this method, Excel displays a warning dialog box. You can use the Application object's properties to prevent this DisplayAlerts warning dialog box appears, this property will be discussed in a "box alarm control and display Excel" earlier in this chapter.

You can hide a worksheet to complete its tab is not displayed by using the Visible property. Visible property type is XlSheetVisibility, you may be provided xlSheetVisible, xlSheetHidden and xlSheetVeryHidden. The last value hidden worksheet so only by setting the Visible property to display again xlSheetVisible. XlSheetHidden the Visible property to hide a worksheet, but you can still go to the "Format" menu and select "Sheet", then click "Hide" to unhide sheets.

Sometimes, using the Visible property to hide a worksheet so that the worksheet can be used to store other data applications used in the "temporary" worksheet users will not see in. VSTO data caching functionality provides a better method, as described in Chapter 18. It has the added advantage that you can hide data in Excel spreadsheet without launching Excel. This allows you to pre-populate an Excel worksheet with custom data on the server.

Please note that the workbook must contain at least one visible worksheet. So when the Delete method and Visible property, you must keep in mind this limitation. If your code attempts to hide or delete workbook last visible form, an exception is thrown.

Listing 5-23 illustrates the use of several of these properties and methods.

Listing 5-23 applies to VSTO customization worksheet collection

Copy the code
private void ThisWorkbook_Startup(object sender, EventArgs e)
{
  Excel.Worksheet sheetA = this.Worksheets.Add(
    missing, missing, missing, missing) as Excel.Worksheet;
  sheetA.Name = "SheetA";

  Excel.Worksheet sheetB = this.Worksheets.Add(
    missing, missing, missing, missing) as Excel.Worksheet;
  sheetB.Name = "SheetB";

  Excel.Worksheet sheetC = this.Worksheets.Add(
    missing, missing, missing, missing) as Excel.Worksheet;
  sheetC.Name = "SheetC";

  // Tab indexes
  string msg = "{0} is at tab index {1}";
  MessageBox.Show(String.Format(msg, sheetA.Name, sheetA.Index));
  MessageBox.Show(String.Format(msg, sheetB.Name, sheetB.Index));
  MessageBox.Show(String.Format(msg, sheetC.Name, sheetC.Index));

  sheetC.Move(sheetA, missing);
  MessageBox.Show("Moved SheetC in front of SheetA");

  // Tab indexes
  MessageBox.Show(String.Format(msg, sheetA.Name, sheetA.Index));
  MessageBox.Show(String.Format(msg, sheetB.Name, sheetB.Index));
  MessageBox.Show(String.Format(msg, sheetC.Name, sheetC.Index));

  sheetB.Copy(sheetA, missing);
  Excel.Worksheet sheetD = this.Worksheets.get_Item(
    sheetA.Index - 1) as Excel.Worksheet;

  ((Excel._Worksheet)sheetA).Activate();

  MessageBox.Show(String.Format(
    "Copied SheetB to create {0} at tab index {1}",
    sheetD.Name, sheetD.Index));

  sheetD.Delete();
  sheetA.Visible = Excel.XlSheetVisibility.xlSheetHidden;
  MessageBox.Show("Deleted SheetD and hid SheetA.");
}
Copy the code

Use the name
mentioned, you can use Workbook.Names named range in the workbook level definition. You can also define a named range in scope to a particular worksheet by using the attributes associated with the Names Worksheet object. Names property returns a name Names containing only the scope of the job table set. For more information about the Names collection, see earlier in this chapter, "using the name of the collection and the name of the object" section.

Use the worksheet custom properties
You can add custom properties have names and values into the worksheet. Custom property is a convenient way to hide information and do not want to put other cells in the worksheet associated. Different from the document properties associated with the workbook, Excel user interface is not anywhere to display custom properties. Worksheet-level custom property does not have a limit of 256 characters for its document property values of. You can store larger blocks of data in the worksheet custom properties.

CustomProperties property returns a set of custom properties associated with the worksheet. You can add custom attributes CustomProperties collection using the Add method, passing a string for the name of the custom property to be created and to be passed associated with the custom value of the property of an object. To get specific custom properties, use CustomProperties.Item method and pass the property to get the index. Unfortunately, Item method requires only the name of a custom property based indexing, instead you add. Therefore, you have to walk through the collection and check each object's Name property CustomProperty return to determine whether you have found the desired custom attributes. Listing 5-24 shows an example of creating a custom attribute, and then visit again.

Listing 5-24 access the custom objects VSTO custom DocumentProperty

Copy the code
private void ThisWorkbook_Startup(object sender, EventArgs e)
{
  Excel.Worksheet sheet = this.Worksheets.Add(missing,
    missing, missing, missing) as Excel.Worksheet;

  // Add a custom property

  Excel.CustomProperties props = sheet.CustomProperties;

  props.Add("myProperty", "Some random value");
  props.Add("otherProperty", 1);

  // Now, enumerate the collection to find myProperty again.
  foreach (Excel.CustomProperty prop in props)
  {
    if (prop.Name == "myProperty")
    {
      MessageBox.Show(String.Format(
        "{0} property is set to {1}.",
        prop.Name, prop.Value));
      break;
    }
  }
}
Copy the code

If you are using VSTO code associated with the workbook, the cached data is usually best to use instead of custom attributes. Cached data functions can be set and any XML data types can be placed in sequence data island in the document. The island can also access data on the server without starting Excel. For more information about VSTO data caching function, see Chapter 18.

Protect Sheet
Protect method to protect a worksheet so that users can not modify the worksheet. When the protective sheet using the Protect method, all the cells in the workbook are automatically locked. Protection method corresponding to FIG. 5-3 "Protecting Sheet" dialog box. You can choose Tools> Protection> page to access the dialog box.


Figure 5-3 Protect Sheet dialog box.

Protect passed to process some optional parameters can be accurately controlled to modify the content, as shown in Table 5-14. Many of these options correspond to the check list shown in Figure 5-3.

Table 5-14 optional parameter protection method

 

 

 

When the worksheet is protected, you have two methods to exclude certain range of cells is locked. The first method is to use a set of AllowEditRanges returned from Worksheet.Protection.AllowEdit-Ranges add exclusions. AllowEditRanges set corresponding to the dialog box allows the user to edit the range shown in Figure 5-4. You can choose Tools> Protection> Allow users to edit the range to access this dialog.


Figure 5-4 dialog allows the user to edit the range

 

You must use AllowEditRanges collection exclude, then use the Protect method to protect a worksheet. After protect the worksheet, before re-unprotect worksheet, AllowEditRanges can not make any changes to the collection. In this way were ruled out, it can be given a title, and displayed in the "Allow users to edit range" dialog box. In this way excluded from the scope of protection thereof from Range.AllowEdit property returns TRue. Listing 5-25 shows a custom VSTO, it uses AllowEditRanges create two protected exclude, then use the Protect method to protect a worksheet.

清单5-25  使用AllowEditRanges将禁止添加到保护的VSTO自定义

 

Copy the code
private void ThisWorkbook_Startup(object sender, EventArgs e)
{
  Excel.Worksheet sheet = this.Worksheets.Add(missing,
    missing, missing, missing) as Excel.Worksheet;

  Excel.AllowEditRanges allowEdits = sheet.Protection.
    AllowEditRanges;

  allowEdits.Add("Editable Cell",
    sheet.get_Range("A1", missing), missing);

  sheet.Protect(missing, missing, missing, missing,
    missing, missing, missing, missing, missing,
    missing, missing, missing, missing, missing,
    missing, missing);

  Excel.Range protectedRange = sheet.get_Range("A2", missing);


  MessageBox.Show(String.Format(
    "A2's Locked is set to {0}", protectedRange.Locked));

  MessageBox.Show(String.Format(
    "A2's AllowEdit is set to {0}", protectedRange.AllowEdit));

  try
  {
    protectedRange.Value2 = "Should fail";
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }

  try
  {
    allowEdits.Add("This should fail",
      sheet.get_Range("A2", missing), missing);
  }
  catch (Exception ex)
  {
    // You can't add to the AllowEditRanges collection
    // when the worksheet is protected
    MessageBox.Show(ex.Message);
  }

  Excel.Range allowEditRange = sheet.get_Range("A1", missing);

  MessageBox.Show(String.Format(
    "A1's Locked is set to {0}", allowEditRange.Locked));

  MessageBox.Show(String.Format(
    "A1's AllowEdit is set to {0}", allowEditRange.AllowEdit));

  allowEditRange.Value2 = "Should succeed";
}
Copy the code

当工作表被保护时,排除某些范围的单元格被锁定的第二种方法是使用Range.Locked属性。 以这种方式排除的单元格不会显示在“允许用户编辑范围”对话框中。 清单5-26显示了使用Range.Locked属性添加排除对保护。

清单5-26 使用Range.Locked添加排除对象的VSTO自定义

 

Copy the code
private void ThisWorkbook_Startup(object sender, EventArgs e)
{
  Excel.Worksheet sheet = this.Worksheets.Add(missing,
    missing, missing, missing) as Excel.Worksheet;

  Excel.Range range1 = sheet.get_Range("A2", missing);
  range1.Locked = false;

  sheet.Protect(missing, missing, missing, missing,
    missing, missing, missing, missing, missing,
    missing, missing, missing, missing, missing,
    missing, missing);

  MessageBox.Show(String.Format(
    "A2's Locked is set to {0}", range1.Locked));

  MessageBox.Show(String.Format(
    "A2's AllowEdit is set to {0}", range1.AllowEdit));

  range1.Value2 = "Should succeed";
}
Copy the code

工作表受保护后,可以通过多个属性来检查文档的保护设置,并进一步修改保护选项,如表5-15所示。

表5-15  允许您检查并进一步修改文档保护的属性

 

使用OLEObjects
除了包含单元格,工作表还可以包含来自其他程序(如嵌入式Word文档)和ActiveX控件的嵌入对象。要使用这些对象,可以在Worksheet对象上使用OLEObjects方法。 OLEObjects方法接受一个可选的Index对象参数,您可以传递OLEObject的名称或集合中OLEObject的基于1的索引。 OLEObjects方法也可以作为一种访问OLEObjects集合的方式,这可能令人困惑。如果你传递一个字符串,它表示为一个名字或一个基于1的索引作为一个int,它返回指定的OLEObject。如果您传递它Type.Missing,它返回OLEObjects集合。

任何时候,将OLEObject添加到工作表中,Excel还包括从“工作表”对象中的“样式”属性返回的“形状”集合中的该对象。要获取OLEObject唯一的属性,可以使用Shape.OLEFormat属性。

可以编写将ActiveX控件添加到工作表中的C#代码,并通过将OLEObject.Object或Shape.OLEFormat.Object转换为适当的类型与它们进行交谈。您必须在C#项目中添加与要使用的ActiveX控件相关联的COM库的引用。这样做会导致Visual Studio生成一个互操作程序集并将其添加到您的项目中。或者,如果为COM库注册了主互操作程序集,Visual Studio将自动添加对预生成的主互操作程序集的引用。然后,您可以将OLEObject.Object或Shape.OLEFormat.Object转换为Visual Studio为与ActiveX控件相对应的COM库对象添加的正确类型。

VSTO使您能够将Windows Forms控件添加到工作表中,功能更强大,以.NET为中心的处理控件的方式。因此,我们不会在本书中更多地使用ActiveX控件。有关VSTO对Windows Forms控件的支持的更多信息,请参见第14章“在VSTO中使用Windows窗体”。

使用形状
Shapes属性返回Shape对象的Shapes集合集合。 Shape对象表示可以插入到Excel电子表格中的各种对象,包括图形,AutoShape,艺术字,嵌入对象或ActiveX控件或图片。

“形状”集合具有“Count”属性,用于确定“工作表”中有多少个形状。它还有一个Item方法,它采用基于1的索引来获取集合中的特定形状。您还可以使用foreach枚举Shapes集合。

“形状”集合上的几种方法可以添加可以表示为“形状”的各种对象。这些方法包括AddCallout,AddConnector,AddCurve,AddDiagram,AddLabel,AddLine,AddOLEObject,AddPicture,AddPolyline,AddShape,AddTextbox和AddTextEffect。

Shape对象具有将Shape置于工作表上的属性和方法。它还具有允许格式化和修改Shape对象的属性和方法。 Shape对象上的属性返回的一些对象如图3-20所示。

使用ChartObjects
在本书中,当引用工作簿中的工作表的图表时,我们使用了短语图表。图5-5显示了在插入新图表时显示的图表向导的最后一页。 Excel使您能够将图表插入新的图表,我们称之为图表单,并允许您将图表作为对象添加到工作表中。对象模型调用在表单中添加为对象的图表。


图5-5 图表向导的图表位置步骤

事情更复杂的是,图表表的对象模型中的对象是一个图表,但ChartObject也有一个返回图表的属性。 ChartObject具有自己的一组属性,用于控制工作表中图表的位置。但是,由ChartObject.Chart属性返回的Chart对象可以找到实际操作图表内容的属性和方法。

要使用ChartObjects,可以在Worksheet对象上使用ChartObjects方法。 ChartObjects方法接受类型对象的可选索引参数,您可以传递集合中ChartObject的名称或ChartObject的基于1的索引。 ChartObjects方法也可以作为获取ChartObjects集合的一种方式,这可能会令人困惑。如果您传递一个表示为名称或基于1的索引的字符串,则返回指定的ChartObject。如果您传递它Type.Missing,它返回ChartObjects集合。

要将ChartObject添加到工作表中,可以使用ChartObjects.Add方法,它将“左”,“顶”,“宽”和“高”作为点的双精度值。每当您将ChartObject添加到工作表中时,Excel也会在“工作表”对象中的“Shapes”属性返回的“Shapes”集合中包含该对象。

使用列表
Excel 2003引入了从一系列单元格创建列表的功能。只需选择一系列单元格,右键单击选择,然后选择创建列表。列表具有列标题和下拉选项,使用户可以轻松地对列表中的数据进行排序和应用过滤器。它有一个总计行,可以自动求和并对一列数据执行其他操作。它在列表底部有一个标有星号的插入行,允许用户向列表中添加其他行。图5-6显示了Excel中的列表示例。


图5-6  Excel中的列表

You can use the list ListObjects property to access the worksheet. ListObjects property returns ListObjects collection. ListObjects collection has a Count property to determine how much of the Worksheet list. It is also a method of Item, it acquires a ListObject from a collection object as a string or an index based on the name list object index. You can also use the foreach enumeration ListObjects collection.

Table 5-16 shows some of the most commonly used properties ListObject object. You will discuss support for more information VSTO data in Chapter 17 "VSTO Data Programming".

Table 5-16 ListObject key attributes of

 

Guess you like

Origin www.cnblogs.com/qiys/p/11367308.html