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

  1. // C#
  2. try
  3. {
  4. ThisApplication.ScreenUpdating = false;
  5. // Do your work that updates the screen.
  6. }
  7. finally
  8. {
  9. ThisApplication.ScreenUpdating = true;
  10. }

下面再介绍几个有关属性:


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

  1. Excel.Workbook wb = ThisApplication.Workbooks.Add(Type.Missing);

2.    关闭workbook

[csharp] view plaincopy

  1. ThisApplication.Workbooks.Close();

3.    打开一个存在的workbook

[csharp] view plaincopy

  1. Excel.Workbook wb = ThisApplication.Workbooks.Open(
  2. "C:\\YourPath\\Yourworkbook.xls",
  3. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  4. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  5. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  6. Type.Missing, Type.Missing);

4.    用Excel的方式打开XML文件,数据库文件或者TXT文件

OpenXML,OpenDatabase,OpenText

5.    通过名字或者索引引用workbook

[csharp] view plaincopy

  1. Excel.Workbook wb = ThisApplication.Workbooks[1];
  2. wb = ThisApplication.Workbooks["Book1"];//在workbook未保存的情况下
  3. 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

  1. // C#
  2. // When the workbook opens:
  3. ThisApplication.get_Range("DefaultFilePath", Type.Missing).
  4. Value2 = ThisApplication.DefaultFilePath;
  5. // When you save the DefaultFilePath property:
  6. ThisApplication.DefaultFilePath =
  7. ThisApplication.get_Range("DefaultFilePath", Type.Missing).
  8. Value2.ToString();

l  默认的保存文件格式 DefaultSaveFormat

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

[csharp] view plaincopy

  1. // 例1
  2. // When the workbook opens, convert the enumerated value
  3. // into a string:
  4. //获得默认的保存格式属性DefaultSaveFormat
  5. ThisApplication.get_Range("DefaultSaveFormat", Type.Missing).
  6. Value2 = ThisApplication.DefaultSaveFormat.ToString();
  7. //例2.设置该属性,相对比较复杂
  8. // 步骤1.Retrieve the name of the new save format, as a string:
  9. string  strSaveFormat = ThisApplication.
  10. get_Range("DefaultSaveFormat", Type.Missing).
  11. Value2.ToString();
  12. //步骤2
  13. Excel.Range rng = ThisApplication.
  14. get_Range("xlFileFormat", Type.Missing);
  15. Excel.Range rngFind = rng.Find(strSaveFormat,
  16. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  17. Excel.XlSearchDirection.xlNext, Type.Missing, Type.Missing,
  18. Type.Missing);
  19. // In C#, use the get_Offset method instead of the Offset property:
  20. int intSaveFormat =
  21. Convert.ToInt32(rngFind.get_Offset(0, 1).Value2);
  22. //步骤3.
  23. ThisApplication.DefaultSaveFormat =
  24. Excel.XlFileFormat) intSaveFormat;

l  RecentFiles属性

[csharp] view plaincopy

  1. // 列出最近打开的文档<strong>
  2. </strong>private void ListRecentFiles()
  3. {
  4. Excel.Range rng = (Excel.Range)ThisApplication.
  5. get_Range("RecentFiles", Type.Missing).Cells[1, 1];
  6. for (int i = 1; i <= ThisApplication.RecentFiles.Count; i++)
  7. {
  8. rng.get_Offset(i - 1, 0).Value2 =
  9. ThisApplication.RecentFiles[i].Name;
  10. }
  11. }

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

  1. // C#
  2. using Office = Microsoft.Office.Core;

执行打开文件对话框的show()函数,将显示该对话框。用户点击OK,则该函数返回-1,若点击Cancel,则该函数返回0。

[csharp] view plaincopy

  1. // 打开FileDialog,选择一个文件打开
  2. dlg = ThisApplication.get_FileDialog(
  3. Office.MsoFileDialogType.msoFileDialogOpen);
  4. dlg.Filters.Clear();
  5. dlg.Filters.Add("Excel Files", "*.xls;*.xlw", Type.Missing);
  6. dlg.Filters.Add("All Files", "*.*", Type.Missing);
  7. if(dlg.Show() != 0)
  8. 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

  1. ThisApplication.get_Range("WorkbookName", Type.Missing).
  2. Value2 = ThisWorkbook.Name;
  3. ThisApplication.get_Range("WorkbookPath", Type.Missing).
  4. Value2 = ThisWorkbook.Path;
  5. ThisApplication.get_Range("WorkbookFullName", Type.Missing).
  6. Value2 = ThisWorkbook.FullName;
  • Password(给EXCEL文件加密)

[csharp] view plaincopy

  1. private void SetPassword()
  2. {
  3. Password frm = new Password();
  4. if (frm.ShowDialog() == DialogResult.OK)
  5. ThisWorkbook.Password = frm.Value;
  6. frm.Dispose();
  7. }
  • PrecisionAsDisplayed

[csharp] view plaincopy

  1. private void TestPrecisionAsDisplayed(
  2. bool IsPrecisionAsDisplayedOn)
  3. {
  4. ThisWorkbook.PrecisionAsDisplayed =
  5. IsPrecisionAsDisplayedOn;
  6. }
  • ReadOnly  (boolean)    返回当前打开的文件是否是只读的
  • Saved        (boolean)    设置/获取 saved state

Working with Styles

[csharp] view plaincopy

  1. // 风格设置
  2. private void ApplyStyle()
  3. {
  4. const String STYLE_NAME = "PropertyBorder";
  5. // Get the range containing all the document properties.
  6. Excel.Range rng = GetDocPropRange();
  7. Excel.Style sty;
  8. try
  9. {
  10. sty = ThisWorkbook.Styles[STYLE_NAME];
  11. }
  12. catch
  13. {
  14. sty = ThisWorkbook.Styles.Add(STYLE_NAME, Type.Missing);
  15. }
  16. sty.Font.Name = "Verdana";
  17. sty.Font.Size = 12;
  18. sty.Font.Color = ColorTranslator.ToOle(Color.Blue);
  19. sty.Interior.Color = ColorTranslator.ToOle(Color.LightGray);
  20. sty.Interior.Pattern = Excel.XlPattern.xlPatternSolid;
  21. rng.Style = STYLE_NAME;
  22. rng.Columns.AutoFit();
  23. }
  24. private Excel.Range GetDocPropRange()
  25. {
  26. Excel.Range rng =
  27. ThisApplication.get_Range("DocumentProperties", Type.Missing);
  28. Excel.Range rngStart =
  29. (Excel.Range) rng.Cells[1, 1];
  30. Excel.Range rngEnd =
  31. rng.get_End(Excel.XlDirection.xlDown).get_Offset(0, 1);
  32. return ThisApplication.get_Range(rngStart, rngEnd);
  33. }

设置风格后的样子:

当然,设置Style后也可以清除Style

[csharp] view plaincopy

  1. // C#
  2. private void ClearStyle()
  3. {
  4. // Get the range containing all the document properties, and
  5. // clear the style.
  6. GetDocPropRange().Style = "Normal";
  7. }

Working with Sheets

[csharp] view plaincopy

  1. // C# 列出所有Sheet
  2. private void ListSheets()
  3. {
  4. int i = 0;
  5. Excel.Range rng =
  6. ThisApplication.get_Range("Sheets", Type.Missing);
  7. foreach (Excel.Worksheet sh in ThisWorkbook.Sheets)
  8. {
  9. rng.get_Offset(i, 0).Value2 = sh.Name;
  10. i = i + 1;
  11. }
  12. }

----------------------------------------------华丽分割-----------------------------------------------

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

  1. // C#
  2. WorksheetObject.Protect(Password, DrawingObjects, Contents,
  3. Scenarios, UserInterfaceOnly, AllowFormattingCells,
  4. AllowFormattingColumns, AllowFormattingRows,
  5. AllowInsertingColumns, AllowInsertingRows,
  6. AllowInsertingHyperlinks, AllowDeletingColumns,
  7. AllowDeletingRows, AllowSorting, AllowFiltering,
  8. AllowUsingPivotTables);

上面的Protect方法有很多参数,分别对应保护的内容。

  • Password  对应密码,当你要撤销保护时需要指定密码
  • DrawingObjects    保护Shapes on the worksheet
  • Contents         保护cells,即所有单元格内容
  • Scenarios        保护情景
  • UserInterfaceOnly      允许通过代码修改,不允许通过用户界面修改AllowFormattingCells AllowFormattingColumns….后面不再赘述

下面这个例子,设置了密码,同时只允许Sorting

[csharp] view plaincopy

  1. // C#
  2. ((Excel.Worksheet)ThisApplication.Sheets[1]).Protect(
  3. "MyPassword", Type.Missing, Type.Missing, Type.Missing,
  4. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  5. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  6. Type.Missing, true, Type.Missing, Type.Missing);

下面的代码展示如何去保护(提示让用户输入密码)

[csharp] view plaincopy

  1. // C#
  2. ((Excel.Worksheet)ThisApplication.Sheets[1]).
  3. 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

  1. // C#
  2. private void ProtectSheet()
  3. {
  4. Excel.Worksheet ws =
  5. (Excel.Worksheet)ThisApplication.ActiveSheet;
  6. Excel.AllowEditRanges ranges = ws.Protection.AllowEditRanges;
  7. ranges.Add("Information",
  8. ThisApplication.get_Range("Information", Type.Missing),
  9. Type.Missing);
  10. ranges.Add("Date",
  11. ThisApplication.get_Range("Date", Type.Missing), Type.Missing);
  12. ws.Protect(Type.Missing, Type.Missing, Type.Missing,
  13. Type.Missing, Type.Missing,Type.Missing, Type.Missing,
  14. Type.Missing,Type.Missing, Type.Missing, Type.Missing,
  15. Type.Missing,Type.Missing,Type.Missing,
  16. Type.Missing,Type.Missing);
  17. }
  18. private void UnprotectSheet()
  19. {
  20. Excel.Worksheet ws =
  21. (Excel.Worksheet) ThisApplication.Sheets["Worksheet Class"];
  22. ws.Unprotect(Type.Missing);
  23. // Delete all protection ranges, just to clean up.
  24. // You must loop through this using the index,
  25. // backwards. This collection doesn‘t provide
  26. // an enumeration method, and it doesn‘t handle
  27. // being resized as you‘re looping in a nice way.
  28. Excel.AllowEditRanges ranges = ws.Protection.AllowEditRanges;
  29. for (int i = ranges.Count; i >= 1; i--)
  30. {
  31. ranges[i].Delete();
  32. }
  33. }

3.3  Object Properties

Worksheet类提供了一些属性(that return objects),下面介绍两个有用属性:

Comments以及Outline

3.3.1  Comments (批注)

在Excel2007中,选中一块区域或者单元格后,点击右键,可以插入批注。插入批注后的样子如下图所示

Worksheet类提供Comments属性,通过该属性,你可以访问该工作表内的所有批注。Comments类没有多少属性,你可能会使用Visible属性来控制批注的显示与隐藏,Delete属性来删除批注,或者你可能会发现Text方法比较有用,因为可以通过它来给批注增加内容或者重写批注。

下面是一个及其简单的例子,来控制显示批注

[csharp] view plaincopy

  1. // C#
  2. private void ShowOrHideComments(bool show)
  3. {
  4. // Show or hide all the comments:
  5. Excel.Worksheet ws =
  6. (Excel.Worksheet) ThisApplication.Sheets["Worksheet Class"];
  7. for (int i = 1; i <= ws.Comments.Count; i++)
  8. {
  9. ws.Comments[i].Visible = show;
  10. }
  11. }

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

  1. // C#
  2. private void WorkWithGroups()
  3. {
  4. Excel.Worksheet ws =
  5. (Excel.Worksheet) ThisApplication.ActiveSheet;
  6. // Set worksheet-level features for the outline.
  7. // In this case, summary rows are below
  8. // the data rows (so Excel knows where to put
  9. // the summary rows), and we don‘t want Excel
  10. // to format the summary rows--that‘s already been done.
  11. ws.Outline.SummaryRow = Excel.XlSummaryRow.xlSummaryBelow;
  12. ws.Outline.AutomaticStyles = false;
  13. // Group the two named ranges. Each of these
  14. // ranges extends across entire rows.
  15. ThisApplication.get_Range("Data2001", Type.Missing).
  16. Group(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  17. ThisApplication.get_Range("Data2002", Type.Missing).
  18. Group(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  19. ThisApplication.get_Range("AllData", Type.Missing).
  20. Group(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  21. // The range of rows from 24 to 27 doesn‘t have
  22. // a named range, so you can work with that
  23. // range directly.
  24. Excel.Range rng = (Excel.Range)ws.Rows["24:27", Type.Missing];
  25. rng.Group(Type.Missing, Type.Missing, Type.Missing,
  26. Type.Missing);
  27. // Collapse to the second group level.
  28. ws.Outline.ShowLevels(2, Type.Missing);
  29. }

对于unnamed range,方法如下:

[csharp] view plaincopy

  1. // C#
  2. Excel.Range rng = (Excel.Range)ws.Rows["24:27", Type.Missing];
  3. rng.Group(Type.Missing, Type.Missing,
  4. Type.Missing, Type.Missing);

在前面的图片中点击Clear Groups link将清除Groups,对应代码如下:

[csharp] view plaincopy

  1. // C#
  2. private void ClearGroups()
  3. {
  4. Excel.Worksheet ws =
  5. (Excel.Worksheet) ThisWorkbook.Sheets["Worksheet Class"];
  6. // Specify RowLevels and/or ColumnLevels parameters:
  7. ws.Outline.ShowLevels(3, Type.Missing);
  8. Excel.Range rng = (Excel.Range) ws.Rows["24:27", Type.Missing];
  9. rng.Ungroup();
  10. ThisApplication.get_Range("Data2001", Type.Missing).Ungroup();
  11. ThisApplication.get_Range("Data2002", Type.Missing).Ungroup();
  12. ThisApplication.get_Range("AllData", Type.Missing).Ungroup();
  13. }

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

  1. // C#
  2. ThisApplication.ActiveCell.CurrentRegion.Select();
  3. ((Excel.Range)ThisApplication.Selection).ClearContents();

 

4.2  Referring to a Range in Code

1)    基本的引用Range方法

1.   引用ActiveCell

[csharp] view plaincopy

  1. rng = ThisApplication.ActiveCell;

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

[csharp] view plaincopy

  1. // C#
  2. rng = ws.get_Range("A1", Type.Missing);
  3. rng = ws.get_Range("A1:B12", Type.Missing);

3.   使用Cells属性

[csharp] view plaincopy

  1. // C#
  2. rng = (Excel.Range)ws.Cells[1, 1];

4.   指定Range的角,同时可以直接引用该Range的Cells Rows Columns属性

[csharp] view plaincopy

  1. // C#
  2. rng = ws.get_Range("A1", "C5");
  3. rng = ws.get_Range("A1", "C5").Cells;
  4. rng = ws.get_Range("A1", "C5").Rows;
  5. rng = ws.get_Range("A1", "C5").Columns;

5.   引用一个带名字的Range

[csharp] view plaincopy

  1. // C#
  2. rng = ThisApplication.Range("SomeRangeName", Type.Missing);

6.   引用特定的行或者列

[csharp] view plaincopy

  1. // C#
  2. rng = (Excel.Range)ws.Rows[1, Type.Missing];
  3. rng = (Excel.Range)ws.Rows["1:3", Type.Missing];
  4. rng = (Excel.Range)ws.Columns[3, Type.Missing];

7.   使用Application对象的Selection方法获取选中Cells对应的Range

执行下面代码,将在调试窗口看到:"$C$3"

[csharp] view plaincopy

  1. // C#
  2. System.Diagnostics.Debug.WriteLine(
  3. ((Excel.Range)ThisApplication.Selection).
  4. get_Address(  Type.Missing, Type.Missing,
  5. Excel.XlReferenceStyle.xlA1,
  6. Type.Missing, Type.Missing)
  7. );

8.   两个Range合并为一个Range

[csharp] view plaincopy

  1. // 简单的合并方法
  2. rng = ThisApplication.get_Range("A1:D4, F2:G5", Type.Missing);
  3. // 相对复杂的合并方法
  4. rng1 = ThisApplication.get_Range("A1", "D4");
  5. rng2 = ThisApplication.get_Range("F2", "G5");
  6. // Note that the Union method requires you to supply thirty
  7. // parameters:
  8. rng = ThisApplication.Union(rng1, rng2,
  9. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  10. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  11. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  12. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  13. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  14. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  15. Type.Missing, Type.Missing, Type.Missing, Type.Missing);

9.   Range的Offset属性

[csharp] view plaincopy

  1. // adds content to the area under the cell at row 1, column 1
  2. rng = (Excel.Range) ws.Cells[1, 1];
  3. for (int i = 1; i <= 5; i++)
  4. {
  5. rng.get_Offset(i, 0).Value2 = i.ToString();//参数1代表Row,2代表Col
  6. }

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

经过上面的介绍,是不是有一点晕呢?下面通过一个小例子来演示一下Range的功能吧。

在使用Excel中,我们可能希望在选中一个单元格后使整行加粗显示,即实现选中效果,但是Excel中没有对该功能的支持。但是,通过代码不难实现该功能,首先看一下实际效果吧。

可以看到,选中的单元格所在行变成了Bold显示。

其实现代码如下:

[csharp] view plaincopy

  1. // C#
  2. private int LastBoldedRow = 0;
  3. private void BoldCurrentRow(Excel.Worksheet ws)
  4. {
  5. // Keep track of the previously bolded row.
  6. // Work with the current active cell.
  7. Excel.Range rngCell = ThisApplication.ActiveCell;
  8. // Bold the current row.
  9. rngCell.EntireRow.Font.Bold = true;
  10. // Make sure intRow isn‘t 0 (meaning that
  11. // this is your first pass through here).
  12. if (LastBoldedRow != 0)
  13. {
  14. // If you‘re on a different
  15. // row than the last time through here,
  16. // make the old row not bold.
  17. if (rngCell.Row != LastBoldedRow)
  18. {
  19. Excel.Range rng =
  20. (Excel.Range)ws.Rows[LastBoldedRow, Type.Missing];
  21. rng.Font.Bold = false;
  22. }
  23. }
  24. // Store away the new row number
  25. // for next time.
  26. LastBoldedRow = rngCell.Row;
  27. }

例子中的workbook通过SheetSelectionChange事件监听器调用BoldCurrentRow方法。

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

[csharp] view plaincopy

  1. // C#
  2. protected void ThisWorkbook_SheetSelectionChange(
  3. System.Object sh, Excel.Range Target)
  4. {
  5. // Don‘t forget that the Intersect method requires
  6. // thirty parameters.
  7. if (ThisApplication.Intersect(Target,
  8. ThisApplication.get_Range("BoldSelectedRow", Type.Missing),
  9. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  10. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  11. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  12. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  13. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  14. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  15. Type.Missing, Type.Missing, Type.Missing, Type.Missing)
  16. != null)
  17. {
  18. // The selection is within the range where you‘re making
  19. //the selected row bold.
  20. BoldCurrentRow((Excel.Worksheet) sh);
  21. }
  22. }

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

  1. // 实现图示自动填充的C#代码
  2. private void AutoFill()
  3. {
  4. Excel.Range rng = ThisApplication.get_Range("B1", Type.Missing);
  5. rng.AutoFill(ThisApplication.get_Range("B1:B5", Type.Missing),
  6. Excel.XlAutoFillType.xlFillDays);
  7. rng = ThisApplication.get_Range("C1", Type.Missing);
  8. rng.AutoFill(ThisApplication.get_Range("C1:C5", Type.Missing),
  9. Excel.XlAutoFillType.xlFillMonths);
  10. rng = ThisApplication.get_Range("D1", Type.Missing);
  11. rng.AutoFill(ThisApplication.get_Range("D1:D5", Type.Missing),
  12. Excel.XlAutoFillType.xlFillYears);
  13. rng = ThisApplication.get_Range("E1:E2", Type.Missing);
  14. rng.AutoFill(ThisApplication.get_Range("E1:E5", Type.Missing),
  15. 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

  1. // C#
  2. private void DemoFind()
  3. {
  4. //得到range对象
  5. Excel.Range rng = ThisApplication.get_Range("Fruits", Type.Missing);
  6. Excel.Range rngFound;
  7. // Keep track of the first range you find.
  8. Excel.Range rngFoundFirst = null;
  9. // You should specify all these parameters
  10. // every time you call this method, since they
  11. // can be overriden in the user interface.
  12. rngFound = rng.Find("apples", Type.Missing,
  13. Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
  14. Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext,
  15. false, Type.Missing, Type.Missing);
  16. while (rngFound != null)
  17. {
  18. if (rngFoundFirst == null )
  19. {
  20. rngFoundFirst = rngFound;
  21. }
  22. else if (GetAddress(rngFound) == GetAddress(rngFoundFirst))
  23. {
  24. break;
  25. }
  26. rngFound.Font.Color = ColorTranslator.ToOle(Color.Red);
  27. rngFound.Font.Bold = true;
  28. rngFound = rng.FindNext(rngFound);
  29. }
  30. }

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

[csharp] view plaincopy

  1. // 取消查找结构的显示
  2. private void ResetFind()
  3. {
  4. Excel.Range rng = ThisApplication.
  5. get_Range("Fruits", Type.Missing);
  6. rng.Font.Color = ColorTranslator.ToOle(Color.Black);
  7. rng.Font.Bold = false;
  8. }

-----------------------------------------华丽分割-----------------------------------

OK,终于写完了。本文主要介绍了Excel的几大对象,主要介绍的是一些API。后面将会通过实例,结合 VS2010,用C#来实现对Excel的操作。感谢阅读。

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

本文的PDF版本下载:点此下载

时间: 2024-08-26 18:24:56

C#操作Excel(1)Excel对象模型的相关文章

DAY6 - os补充操作,发邮件,数据库操作,写excel,加密操作

1.Map-循环帮你调用函数 **生成器的概念** 输出为: map返回的就是一个生成器 2.filter-把函数处理结果为false的结果过滤掉 比较map和filter的输出: 3.os的目录操作 4.OS里执行系统命令 我们可能会用到的一个查看系统日志的命令: os.popen('top -n 1').read() 5.datetime模块 输出为: 输出为一个datetime的类型,如: 输出为: 6.Random模块 输出为: 7.Log模块 8.发邮件 第一步:需要先安装发邮件的模块

c#.net对excel的操作——创建一个excel报表两个sheet就是2个表分别添加内容

添加引用:Microsoft.Office.Interop.Excel //创建excel对象,就是实例化一个excel对象            Application excel=new Application();            //设置工作表的个数            excel.SheetsInNewWorkbook=2;            //创建Wprkbook            excel.Workbooks.Add();            //取出第一个工

C#操作office进行Excel图表创建,保存本地,word获取

1,新建C#控制台应用程序(Excel创建图表) using System; using System.Collections.Generic; using System.Linq; using System.Text; //解决方案中 添加引用 Execl(COM组件) using MSExcel = Microsoft.Office.Interop.Excel; using System.IO; using System.Reflection; namespace ExeclCharts {

[Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你!

引言 项目中常用到将数据导入Excel,将Excel中的数据导入数据库的功能,曾经也查找过相关的内容,将曾经用过的方案总结一下. 方案一 NPOI NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作

服务器不装Excel读取Excel并转换DataTable

原来是用OleDb.4.0组件读取Excel,但是放到服务器后 傻了,服务器没装Excel ,而且领导说不可以装 没办法,只好自己重新找下代码 在CodeProject找到一个开源的dll,一阵欢喜啊,虽然是winform项目,但是主要是用他的类库所以提取一下后 自己研究后重新封装了一个类,运行 耶! 完美支持 需要Dome的同学下载后去研究下吧 地址:http://download.csdn.net/detail/jine515073/7266371 本人用 Excel 97-2003 工作表

在 Laravel 5 中使用 Laravel Excel 实现 Excel/CSV 文件导入导出功能(转)

1.简介 Laravel Excel 在 Laravel 5 中集成 PHPOffice 套件中的 PHPExcel ,从而方便我们以优雅的.富有表现力的代码实现Excel/CSV文件的导入和 导出 . 该项目的GitHub地址是: https://github.com/Maatwebsite/Laravel-Excel . 本文我们将在Laravel中使用Laravel Excel简单实现Excel文件的导入和导出. 2.安装&配置 使用Composer安装依赖 首先在Laravel项目根目录

在 Laravel 5 中使用 Laravel Excel 实现 Excel/CSV 文件导入导出功能

1.简介 Laravel Excel 在 Laravel 5 中集成 PHPOffice 套件中的 PHPExcel ,从而方便我们以优雅的.富有表现力的代码实现Excel/CSV文件的导入和 导出 . 该项目的GitHub地址是: https://github.com/Maatwebsite/Laravel-Excel . 本文我们将在Laravel中使用Laravel Excel简单实现Excel文件的导入和导出. 2.安装&配置 使用Composer安装依赖 首先在Laravel项目根目录

PHP excel reader , excel时间转成php时间格式

最近,在做一个导入功能,在系统中使用PHPExcel类库,读取上传的Excel文件,然后进行字段映射,最后将Excel内的数据导入到系统中.其中,关于日期格式的导入,使我犯了难. 首先,如何导入日期,因为PHPExcel中日期格式在获取时得到的是数字,并不是日期字符串,于是,网上就有许多代码,用于将Excel中获取的数字转换成PHP使用的Unix Time,其实不必这么麻烦.PHPExcel中就有这样的方法:PHPExcel_Shared_Date::ExcelToPHP($value) .可以

使用 Laravel Excel 实现 Excel/CSV 文件导入导出功能

一.安装配置 使用Composer安装依赖: composer require maatwebsite/excel 发布配置(可选): php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" 配置config/app.php的providers和aliases(可选): 'providers' => [ /* * Package Service Providers... */ M

[Excel]利用 Excel 2012 读取 SQL Server 数据库

进入 Excel 之后,选择"数据"→"从其他来源"→"从 SQL Server" 选择要连接的数据库,输入"服务器名称"和"登入认证"的资讯. 挑选数据库和数据表 完成数据设定 一般来说按下"确定"就可以了:如果担心数据过重载入过久的话,可以选择"内容",来做进一步的调整 此时可以选择"定义"的页签,将"命令类型"更改为&qu