title | description | ms.date | ms.topic | dev_langs | helpviewer_keywords | author | ms.author | manager | ms.technology | ms.workload | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Excel Object model overview |
Learn that you can interact with the objects provided by the Excel object model to develop solutions that use Microsoft Office Excel. |
08/14/2019 |
conceptual |
|
|
John-Hart |
johnhart |
jmartens |
office-development |
office |
Excel object model overview
[!INCLUDE Visual Studio]
To develop solutions that use Microsoft Office Excel, you can interact with the objects provided by the Excel object model. This topic introduces the most important objects:
-
xref:Microsoft.Office.Interop.Excel.Application
-
xref:Microsoft.Office.Interop.Excel.Workbook
-
xref:Microsoft.Office.Interop.Excel.Worksheet
-
xref:Microsoft.Office.Interop.Excel.Range
[!INCLUDEappliesto_xlalldocapp]
[!includeAdd-ins note]
The object model closely follows the user interface. The xref:Microsoft.Office.Interop.Excel.Application object represents the entire application, and each xref:Microsoft.Office.Interop.Excel.Workbook object contains a collection of Worksheet
objects. From there, the major abstraction that represents cells is the xref:Microsoft.Office.Interop.Excel.Range object, which enables you to work with individual cells or groups of cells.
In addition to the Excel object model, Office projects in Visual Studio provide host items and host controls that extend some objects in the Excel object model. Host items and host controls behave like the Excel objects they extend, but they also have additional functionality such as data-binding capabilities and extra events. For more information, see Automate Excel by using extended objects and Host items and host controls overview.
This topic provides a brief overview of the Excel object model. For resources where you can learn more about the entire Excel object model, see Use the Excel object model documentation.
Access objects in an Excel project
When you create a new VSTO Add-in project for Excel, Visual Studio automatically creates a ThisAddIn.vb or ThisAddIn.cs code file. You can access the Application object by using Me.Application
or this.Application
.
When you create a new document-level project for Excel, you have the option of creating a new Excel Workbook or Excel Template project. Visual Studio automatically creates the following code files in your new Excel project for both workbook and template projects.
Visual Basic | C# |
---|---|
ThisWorkbook.vb | ThisWorkbook.cs |
Sheet1.vb | Sheet1.cs |
Sheet2.vb | Sheet2.cs |
Sheet3.vb | Sheet3.cs |
You can use the Globals
class in your project to access ThisWorkbook
, Sheet1
, Sheet2
, or Sheet3
from outside of the respective class. For more information, see Global access to objects in Office projects. The following example calls the xref:Microsoft.Office.Interop.Excel._Worksheet.PrintPreview%2A method of Sheet1
regardless of whether the code is placed in one of the Sheet
n classes or the ThisWorkbook
class.
C#
:::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_VstcoreExcelAutomationCS/Sheet1.cs» id=»Snippet82″:::
VB
:::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_VstcoreExcelAutomation/Sheet1.vb» id=»Snippet82″:::
Because the data in an Excel document is highly structured, the object model is hierarchical and straightforward. Excel provides hundreds of objects with which you might want to interact, but you can get a good start on the object model by focusing on a small subset of the available objects. These objects include the following four:
-
Application
-
Workbook
-
Worksheet
-
Range
Much of the work done with Excel centers around these four objects and their members.
Application object
The Excel xref:Microsoft.Office.Interop.Excel.Application object represents the Excel application itself. The xref:Microsoft.Office.Interop.Excel.Application object exposes a great deal of information about the running application, the options applied to that instance, and the current user objects open within the instance.
[!NOTE]
You should not set the xref:Microsoft.Office.Interop.Excel.ApplicationClass.EnableEvents%2A property of the xref:Microsoft.Office.Interop.Excel.Application object in Excel to false. Setting this property to false prevents Excel from raising any events, including the events of host controls.
Workbook object
The xref:Microsoft.Office.Interop.Excel.Workbook object represents a single workbook within the Excel application.
The Office development tools in Visual Studio extend the xref:Microsoft.Office.Interop.Excel.Workbook object by providing the xref:Microsoft.Office.Tools.Excel.Workbook type. This type gives you access to all features of a xref:Microsoft.Office.Interop.Excel.Workbook object. For more information, see Workbook host item.
Worksheet object
The xref:Microsoft.Office.Interop.Excel.Worksheet object is a member of the xref:Microsoft.Office.Interop.Excel.Worksheets collection. Many of the properties, methods, and events of the xref:Microsoft.Office.Interop.Excel.Worksheet are identical or similar to members provided by the xref:Microsoft.Office.Interop.Excel.Application or xref:Microsoft.Office.Interop.Excel.Workbook objects.
Excel provides a xref:Microsoft.Office.Interop.Excel.Sheets collection as a property of a xref:Microsoft.Office.Interop.Excel.Workbook object. Each member of the xref:Microsoft.Office.Interop.Excel.Sheets collection is either a xref:Microsoft.Office.Interop.Excel.Worksheet or a xref:Microsoft.Office.Interop.Excel.Chart object.
The Office development tools in Visual Studio extend the xref:Microsoft.Office.Interop.Excel.Worksheet object by providing the xref:Microsoft.Office.Tools.Excel.Worksheet type. This type gives you access to all features of a xref:Microsoft.Office.Interop.Excel.Worksheet object, as well as new features such as the ability to host managed controls and handle new events. For more information, see Worksheet host item.
Range object
The xref:Microsoft.Office.Interop.Excel.Range object is the object you will use most within your Excel applications. Before you can manipulate any region within Excel, you must express it as a xref:Microsoft.Office.Interop.Excel.Range object and work with methods and properties of that range. A xref:Microsoft.Office.Interop.Excel.Range object represents a cell, a row, a column, a selection of cells that contains one or more blocks of cells, which might or might not be contiguous, or even a group of cells on multiple sheets.
Visual Studio extends the xref:Microsoft.Office.Interop.Excel.Range object by providing the xref:Microsoft.Office.Tools.Excel.NamedRange and xref:Microsoft.Office.Tools.Excel.XmlMappedRange types. These types have most of the same features as a xref:Microsoft.Office.Interop.Excel.Range object, as well as new features such as the data binding capability and new events. For more information, see NamedRange control and XmlMappedRange control.
Use the Excel object model documentation
For complete information about the Excel object model, you can refer to the Excel primary interop assembly (PIA) reference and the VBA object model reference.
Primary interop assembly reference
The Excel PIA reference documentation describes the types in the primary interop assembly for Excel. This documentation is available from the following location: Excel 2010 primary interop assembly reference.
For more information about the design of the Excel PIA, such as the differences between classes and interfaces in the PIA and how events in the PIA are implemented, see Overview of classes and interfaces in the Office primary interop assemblies.
VBA object model reference
The VBA object model reference documents the Excel object model as it is exposed to Visual Basic for Applications (VBA) code. For more information, see Excel 2010 object model reference.
All of the objects and members in the VBA object model reference correspond to types and members in the Excel PIA. For example, the Worksheet object in the VBA object model reference corresponds to the xref:Microsoft.Office.Interop.Excel.Worksheet object in the Excel PIA. Although the VBA object model reference provides code examples for most properties, methods, and events, you must translate the VBA code in this reference to Visual Basic or Visual C# if you want to use them in an Excel project that you create by using Visual Studio.
Related topics
Title | Description |
---|---|
Excel solutions | Explains how you can create document-level customizations and VSTO Add-ins for Microsoft Office Excel. |
Work with ranges | Provides examples that show how to perform common tasks with ranges. |
Work with worksheets | Provides examples that show how to perform common tasks with worksheets. |
Work with workbooks | Provides examples that show how to perform common tasks with workbooks. |
This C# tutorial handles Microsoft Excel files. It applies Microsoft.Office.Interop.Excel to read XLS files.
Excel creates XLS and XLSX files. These files are hard to read in C# programs.
They are handled with the Microsoft.Office.Interop.Excel assembly. This assembly sometimes creates performance issues. Step-by-step instructions are helpful.
Tip: Add the Microsoft.Office.Interop.Excel assembly by going to Project -> Add Reference.
Visual Studio
Interop. You must include a namespace to use Excel in your C# program. You have to use Visual Studio’s GUI to add an assembly to your program to use Excel interop. Use the Add Reference command for this.
Namespace containing Excel interop methods using Microsoft.Office.Interop.Excel;
First, we make a new C# class file in Visual Studio and you can call it something like ExcelInterop. We use that name in the examples, but you are free to use something more familiar or standard.
Tip: Add the using line to your class file—this will make the Excel namespace handy.
Excel interop methods. If you look at various Excel interop objects in IntelliSense, you will see hundreds of undocumented functions. You will only need to use a few—unless you have complex requirements.
Class that stores Application: C# /// <summary> /// This class contains the Excel Interop code we need. /// It can be shared in many places to avoid duplication. /// </summary> class ExcelReaderInterop { /// <summary> /// Store the Application object we can use in the member functions. /// </summary> Application _excelApp; /// <summary> /// Initialize a new Excel reader. Must be integrated /// with an Excel interface object. /// </summary> public ExcelReaderInterop() { _excelApp = new Application(); } }
Interop class. We need a place to store our Excel information, so we use our special class. Put an Application object called _excelApp as a member. In the constructor, make the _excelApp a new Application object.
Class
Open. To open Excel files, you must call Workbooks.Open. It is harder than it should be. Put a public function on the class, and it can use the _excelApp we already have. The following code uses the Workbooks.Open method.
Method that opens Excel workbooks: C# /// <summary> /// Open the file path received in Excel. Then, open the workbook /// within the file. Send the workbook to the next function, the internal scan /// function. Will throw an exception if a file cannot be found or opened. /// </summary> public void ExcelOpenSpreadsheets(string thisFileName) { try { // // This mess of code opens an Excel workbook. I don't know what all // those arguments do, but they can be changed to influence behavior. // Workbook workBook = _excelApp.Workbooks.Open(thisFileName, 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); // // Pass the workbook to a separate function. This new function // will iterate through the worksheets in the workbook. // ExcelScanIntenal(workBook); // // Clean up. // workBook.Close(false, thisFileName, null); Marshal.ReleaseComObject(workBook); } catch { // // Deal with exceptions. // } }
I apologize for the mess that is Workbooks.Open. This is probably the result of legacy code at Microsoft. There are many Type.Missing arguments. And don’t panic over those Type.Missing arguments. You don’t need to know what they do.
Next, open a workbook with Workbooks.Open. Send the workbook we open to another function called ExcelScanInternal. Close the workbook and release all the memory. You will need to deal with exceptions in the catch block.
Note: I don’t have the information about all the detailed exceptions that can be thrown. Just catch them in one statement.
Catch
Loop. To get data from workbooks, you will need to loop over the sheets. An Excel workbook has one or more sheets. In Excel, you can switch between sheets by clicking on the tabs on the bottom.
Tip: In Excel Interop, sheets are indexed starting at 1. This is similar to Visual Basic but not the C# language.
Method that gets sheets: C# /// <summary> /// Scan the selected Excel workbook and store the information in the cells /// for this workbook in an object[,] array. Then, call another method /// to process the data. /// </summary> private void ExcelScanIntenal(Workbook workBookIn) { // // Get sheet Count and store the number of sheets. // int numSheets = workBookIn.Sheets.Count; // // Iterate through the sheets. They are indexed starting at 1. // for (int sheetNum = 1; sheetNum < numSheets + 1; sheetNum++) { Worksheet sheet = (Worksheet)workBookIn.Sheets[sheetNum]; // // Take the used range of the sheet. Finally, get an object array of all // of the cells in the sheet (their values). You can do things with those // values. See notes about compatibility. // Range excelRange = sheet.UsedRange; object[,] valueArray = (object[,])excelRange.get_Value( XlRangeValueDataType.xlRangeValueDefault); // // Do something with the data in the array with a custom method. // ProcessObjects(valueArray); } }
In this example, the object array is directly usable in the C# language. Once you get the objects, you don’t need to do any more Interop. This provides a huge performance boost. There are benefits to reducing calls to Excel Interop.
Next: I show some benchmarks I took comparing the various techniques of Excel interop.
Performance. If you do your Excel processing wrong, you could be waiting a long time to process even 10 spreadsheets at once. Using the Cells[] indexer on a range, or getting the range with the Range property or get_Range() is slow.
Note: This document is based on .NET 3.5. The approach shown here is the fastest one.
Excel interop benchmark Cells[]: 30.0 seconds get_Range(), Cells[]: 15.0 seconds UsedRange, get_Value(): 1.5 seconds [fastest]
Compatibility. There is a compatibility issue with the Excel program on the Apple Mac OS X platform. Excel stores OA dates in different formats on Macs and PCs. The code above shows one solution, which is to use get_Value() instead of Value2.
FromOADate and Excel Dates
Note: The function get_Value() returns objects that do not vary based on the original platform.
Charts. It is also possible to create charts directly in your Excel workbooks. The ChartWizard method is useful for this. Also, you can use new features from the .NET Framework 4.0 to simplify how you use Excel.
This example uses several hard-coded constant values. The range of the data we want to chart is encoded in the topLeft and bottomRight constants. You can see we use the ChartObjects property and then Add a Chart.
Next: We set the range of the chart with SetSourceData. We use the XlChartType.xlLine enumerated constant and call ChartWizard().
Tip: Include the Microsoft.Office.Interop.Excel namespace by right-clicking on References and selecting Add Reference.
C# program that creates Excel chart from data using Microsoft.Office.Interop.Excel; class Program { const string fileName = "C:\Book1.xlsx"; const string topLeft = "A1"; const string bottomRight = "A4"; const string graphTitle = "Graph Title"; const string xAxis = "Time"; const string yAxis = "Value"; static void Main() { // Open Excel and get first worksheet. var application = new Application(); var workbook = application.Workbooks.Open(fileName); var worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet; // Add chart. var charts = worksheet.ChartObjects() as Microsoft.Office.Interop.Excel.ChartObjects; var chartObject = charts.Add(60, 10, 300, 300) as Microsoft.Office.Interop.Excel.ChartObject; var chart = chartObject.Chart; // Set chart range. var range = worksheet.get_Range(topLeft, bottomRight); chart.SetSourceData(range); // Set chart properties. chart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine; chart.ChartWizard(Source: range, Title: graphTitle, CategoryTitle: xAxis, ValueTitle: yAxis); // Save. workbook.Save(); } }
In this example, we use the named parameters and default parameters functionality in the .NET Framework 4.0. In older versions of the .NET Framework, you will need to specify the Missing value yourself.
Note: Some code contributed by Randall Kelsey was adapted for the charting example.
The program requires an Excel document named Book1.xlsx located at C:Book1.xlsx. In this file, you need to add four values in the first column. The program, upon execution, will create a chart based on those four values.
Tip: Many options can be changed to create different charts based on different data ranges.
Also: We showed how named parameters and default parameters from the .NET Framework 4.0 can clean up Microsoft.Office.Interop.Excel code.
Summary. We saw how to get started with Excel interop and avoid severe performance problems with the assembly. It is confusing to call the complicated Open method with Type.Missing in more places than necessary.
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf
Оставляю заметку по работе с Excel с помощью C#.
Привожу фрагменты кода, которые искал когда-то сам для работы с Excel документами.
Наработки очень пригодились в работе для формирования отчетности.
Прежде всего нужно подключить библиотеку Microsoft.Office.Interop.Excel.
Далее создаем псевдоним для работы с Excel:
using Excel = Microsoft.Office.Interop.Excel;
//Объявляем приложение Excel.Application ex = new Microsoft.Office.Interop.Excel.Application(); //Отобразить Excel ex.Visible = true; //Количество листов в рабочей книге ex.SheetsInNewWorkbook = 2; //Добавить рабочую книгу Excel.Workbook workBook = ex.Workbooks.Add(Type.Missing); //Отключить отображение окон с сообщениями ex.DisplayAlerts = false; //Получаем первый лист документа (счет начинается с 1) Excel.Worksheet sheet = (Excel.Worksheet)ex.Worksheets.get_Item(1); //Название листа (вкладки снизу) sheet.Name = "Отчет за 13.12.2017"; //Пример заполнения ячеек for (int i = 1; i <= 9; i++) { for (int j = 1; j < 9; j++) sheet.Cells[i, j] = String.Format("Boom {0} {1}", i, j); } //Захватываем диапазон ячеек Excel.Range range1 = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[9, 9]); //Шрифт для диапазона range1.Cells.Font.Name = "Tahoma"; //Размер шрифта для диапазона range1.Cells.Font.Size = 10; //Захватываем другой диапазон ячеек Excel.Range range2 = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[9, 2]); range2.Cells.Font.Name = "Times New Roman"; //Задаем цвет этого диапазона. Необходимо подключить System.Drawing range2.Cells.Font.Color = ColorTranslator.ToOle(Color.Green); //Фоновый цвет range2.Interior.Color = ColorTranslator.ToOle(Color.FromArgb(0xFF, 0xFF, 0xCC));
Расстановка рамок.
Расставляем рамки со всех сторон:
range2.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; range2.Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; range2.Borders.get_Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous; range2.Borders.get_Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous; range2.Borders.get_Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous;
Цвет рамки можно установить так:
range2.Borders.Color = ColorTranslator.ToOle(Color.Red);
Выравнивания в диапазоне задаются так:
rangeDate.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; rangeDate.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
Формулы
Определим задачу: получить сумму диапазона ячеек A4:A10.
Для начала снова получим диапазон ячеек:
Excel.Range formulaRange = sheet.get_Range(sheet.Cells[4, 1], sheet.Cells[9, 1]);
Далее получим диапазон вида A4:A10 по адресу ячейки ( [4,1]; [9;1] ) описанному выше:
string adder = formulaRange.get_Address(1, 1, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
Теперь в переменной adder у нас хранится строковое значение диапазона ( [4,1]; [9;1] ), то есть A4:A10.
Вычисляем формулу:
//Одна ячейка как диапазон Excel.Range r = sheet.Cells[10, 1] as Excel.Range; //Оформления r.Font.Name = "Times New Roman"; r.Font.Bold = true; r.Font.Color = ColorTranslator.ToOle(Color.Blue); //Задаем формулу суммы r.Formula = String.Format("=СУММ({0}", adder);
Выделение ячейки или диапазона ячеек
Так же можно выделить ячейку или диапазон, как если бы мы выделили их мышкой:
sheet.get_Range("J3", "J8").Activate(); //или sheet.get_Range("J3", "J8").Select(); //Можно вписать одну и ту же ячейку, тогда будет выделена одна ячейка. sheet.get_Range("J3", "J3").Activate(); sheet.get_Range("J3", "J3").Select();
Авто ширина и авто высота
Чтобы настроить авто ширину и высоту для диапазона, используем такие команды:
range.EntireColumn.AutoFit(); range.EntireRow.AutoFit();
Получаем значения из ячеек
Чтобы получить значение из ячейки, используем такой код:
//Получение одной ячейки как ранга Excel.Range forYach = sheet.Cells[ob + 1, 1] as Excel.Range; //Получаем значение из ячейки и преобразуем в строку string yach = forYach.Value2.ToString();
Добавляем лист в рабочую книгу
Чтобы добавить лист и дать ему заголовок, используем следующее:
var sh = workBook.Sheets; Excel.Worksheet sheetPivot = (Excel.Worksheet)sh.Add(Type.Missing, sh[1], Type.Missing, Type.Missing); sheetPivot.Name = "Сводная таблица";
Добавление разрыва страницы
//Ячейка, с которой будет разрыв Excel.Range razr = sheet.Cells[n, m] as Excel.Range; //Добавить горизонтальный разрыв (sheet - текущий лист) sheet.HPageBreaks.Add(razr); //VPageBreaks - Добавить вертикальный разрыв
Сохраняем документ
ex.Application.ActiveWorkbook.SaveAs("doc.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Как открыть существующий документ Excel
ex.Workbooks.Open(@"C:UsersMyuserDocumentsExcel.xlsx", 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);
Комментарии
При работе с Excel с помощью C# большую помощь может оказать редактор Visual Basic, встроенный в Excel.
Для этого в настройках ленты надо добавить пункт «Разработчик». Далее начинаем запись макроса, производим действия и останавливаем запись.
Далее заходим в редактор Visual Basic и смотрим код, который туда записался:
Например:
Sub Макрос1() ' ' Макрос1 Макрос ' ' Range("E88").Select ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$F$118"), , xlYes).Name = _ "Таблица1" Range("A1:F118").Select ActiveSheet.ListObjects("Таблица1").TableStyle = "TableStyleLight9" Range("E18").Select ActiveWindow.SmallScroll Down:=84 End Sub
В данном макросе записаны все действия, которые мы выполнили во время его записи. Эти методы и свойства можно использовать в C# коде.
Данный метод так же может оказать помощь в формировании относительных формул, например, выполнить сложение чисел, находящиеся слева от текущей ячейки на 4 столбца, и т.п. Пример:
//Складываем значения предыдущих 12 ячеек слева rang.Formula = "=СУММ(RC[-12]:RC[-1])";
Так же во время работы может возникнуть ошибка: метод завершен неверно. Это может означать, что не выбран лист, с которым идет работа.
Чтобы выбрать лист, выполните sheetData.Select(Type.Missing);
где sheetData это нужный лист.
Просмотрено:
81 944
-
README
-
Frameworks
-
Dependencies
-
Used By
-
Versions
This an assembly you can use for Excel 2013/2016/2019 COM interop, generated and signed by Microsoft. This is entirely unsupported and there is no license since it is a repackaging of Office assemblies.
Product | Versions |
---|---|
.NET |
net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows |
.NET Core |
netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1 |
.NET Standard |
netstandard2.0 netstandard2.1 |
.NET Framework |
net20 net35 net40 net403 net45 net451 net452 net46 net461 net462 net463 net47 net471 net472 net48 net481 |
MonoAndroid | monoandroid |
MonoMac | monomac |
MonoTouch | monotouch |
Tizen |
tizen40 tizen60 |
Xamarin.iOS | xamarinios |
Xamarin.Mac | xamarinmac |
Xamarin.TVOS | xamarintvos |
Xamarin.WatchOS | xamarinwatchos |
-
.NETFramework 4.0
- No dependencies.
-
.NETStandard 2.0
- No dependencies.
NuGet packages (68)
Showing the top 5 NuGet packages that depend on Microsoft.Office.Interop.Excel:
Package | Downloads |
---|---|
FileHelpers.ExcelStorage Extension for FileHelpers to support Excel read/write operations, using Interop Assemblies (deprecated) www.filehelpers.net |
143.3K |
fion.modelerp.core ModelErp |
112.2K |
BalaReva.Excel.Activities Tha package contains more activities .It make more the excel automation. |
95.1K |
MepApps.MepControls Mep Apps Inc. Base Code Module |
59.6K |
Horseshoe.NET.Excel An Excel file import utility for .NET (uses NPOI) |
29.1K |
GitHub repositories (10)
Showing the top 5 popular GitHub repositories that depend on Microsoft.Office.Interop.Excel:
Repository | Stars |
---|---|
greenshot/greenshot Greenshot for Windows — Report bugs & features go here: https://greenshot.atlassian.net or look for information on: |
3.3K |
Tichau/FileConverter File Converter is a very simple tool which allows you to convert and compress one or several file(s) using the context menu in windows explorer. |
2.6K |
DynamoDS/Dynamo Open Source Graphical Programming for Design |
1.4K |
Excel-DNA/ExcelDna Excel-DNA — Free and easy .NET for Excel. This repository contains the core Excel-DNA library. |
1.0K |
saucepleez/taskt taskt (pronounced ‘tasked’ and formely sharpRPA) is free and open-source robotic process automation (rpa) built in C# powered by the .NET Framework |
802 |
Все привет, в этой статье опишу исчерпывающие примеры работы с excel на языке C#.
Для начала работы нам необходимо подключить библиотеку COM как на рисунке ниже:
Для этого добавляем ссылку в проект, надеюсь вы знаете как это делается) Выбираем пункт COM ищем библиотеку Microsoft Excel 16.0 Object Library ставим галочку и жмем Ок.
Далее нам не обходимо для сокращения записи и удобства создать алиас.
using Excel = Microsoft.Office.Interop.Excel; |
Теперь нам нужно объявить объект Excel задать параметры и приступать к работе.
//Объявляем приложение Excel.Application app = new Excel.Application { //Отобразить Excel Visible = true, //Количество листов в рабочей книге SheetsInNewWorkbook = 2 }; //Добавить рабочую книгу Excel.Workbook workBook = app.Workbooks.Add(Type.Missing); //Отключить отображение окон с сообщениями app.DisplayAlerts = false; //Получаем первый лист документа (счет начинается с 1) Excel.Worksheet sheet = (Excel.Worksheet)app.Worksheets.get_Item(1); //Название листа (вкладки снизу) sheet.Name = «Имя должно быть не больше 32сим»; |
Пример заполнения ячейки:
//Пример заполнения ячеек №1 for (int i = 1; i <= 9; i++) { for (int j = 1; j < 9; j++) sheet.Cells[i, j] = String.Format(«nookery {0} {1}», i, j); } //Пример №2 sheet.Range[«A1»].Value = «Пример №2»; //Пример №3 sheet.get_Range(«A2»).Value2 = «Пример №3»; |
Захват диапазона ячеек:
//Захватываем диапазон ячеек Вариант №1 Excel.Range r1 = sheet.Cells[1, 1]; Excel.Range r2 = sheet.Cells[9, 9]; Excel.Range range1 = sheet.get_Range(r1, r2); //Захватываем диапазон ячеек Вариант №2 Excel.Range range2 = sheet.get_Range(«A1»,«H9» ); |
Оформление, шрифт, размер, цвет, толщина.
//Шрифт для диапазона range.Cells.Font.Name = «Tahoma»; range2.Cells.Font.Name = «Times New Roman»; //Размер шрифта для диапазона range.Cells.Font.Size = 10; //Жирный текст range.Font.Bold = true; //Цвет текста range.Font.Color = ColorTranslator.ToOle(Color.Blue); |
Объединение ячеек в одну
//Объединение ячеек с F2 по K2 Excel.Range range3 = sheet.get_Range(«F2», «K2»); range3.Merge(Type.Missing); |
Изменяем размеры ячеек по ширине и высоте
//увеличиваем размер по ширине диапазон ячеек Excel.Range range2 = sheet.get_Range(«D1», «S1»); range2.EntireColumn.ColumnWidth = 10; //увеличиваем размер по высоте диапазон ячеек Excel.Range rowHeight = sheet.get_Range(«A4», «S4»); rowHeight.EntireRow.RowHeight = 50;range.EntireColumn.AutoFit();range.EntireColumn.AutoFit(); //авторазмер |
Создаем обводку диапазона ячеек
Excel.Range r1 = sheet.Cells[countRow, 2]; Excel.Range r2 = sheet.Cells[countRow, 19]; Excel.Range rangeColor = sheet.get_Range(r1, r2); rangeColor.Borders.Color = ColorTranslator.ToOle(Color.Black); |
Производим выравнивания содержимого диапазона ячеек.
Excel.Range r = sheet.get_Range(«A1», «S40»); //Оформления r.Font.Name = «Calibri»; r.Cells.Font.Size = 10; r.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; r.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; |
Примеры вычисления формул, все вставки формул были скопированы из самой Excel без изменений. Позиция ячейки взята из счетчика переменно и подставлен к букве ячейки
sheet.Cells[countRow, countColumn] = $«=G{countRow}-F{countRow}»; sheet.Cells[countRow, countColumn].FormulaLocal = $«=ЕСЛИ((H{countRow}*O{countRow})+(I{countRow}*P{countRow})/100<=0;J{countRow}*O{countRow}/100;((H{countRow}*O{countRow})+(I{countRow}*P{countRow}))/100)»; sheet.Cells[countRow, countColumn] = $«=K{countRow}+N{countRow}-R{countRow}»; sheet.Cells[33, 22].FormulaLocal = «=СУММ(V3:V32)»; |
Добавляем разрыв страницы.
//Ячейка, с которой будет разрыв Excel.Range razr = sheet.Cells[n, m] as Excel.Range; //Добавить горизонтальный разрыв (sheet — текущий лист) sheet.HPageBreaks.Add(razr); //VPageBreaks — Добавить вертикальный разрыв |
Как открыть фаил Excel
app.Workbooks.Open(@»C:UsersUserDocumentsExcel.xlsx», 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); |
Сохраняем документ Excel
app.Application.ActiveWorkbook.SaveAs(«MyFile.xlsx», Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); |
Завершение работы с объектом Excel.Application
app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); |
Пример как выбрать фаил и загрузив его и узнать количество заполненных строк и колонок в одном конкретном листе по имени.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
//поиск файла Excel OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect =false; ofd.DefaultExt = «*.xls;*.xlsx»; ofd.Filter = «Microsoft Excel (*.xls*)|*.xls*»; ofd.Title = «Выберите документ Excel»; if (ofd.ShowDialog() != DialogResult.OK) { MessageBox.Show(«Вы не выбрали файл для открытия», «Внимание», MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string xlFileName = ofd.FileName; //имя нашего Excel файла //рабоата с Excel Excel.Range Rng; Excel.Workbook xlWB; Excel.Worksheet xlSht; int iLastRow, iLastCol; Excel.Application xlApp = new Excel.Application(); //создаём приложение Excel xlWB = xlApp.Workbooks.Open(xlFileName); //открываем наш файл xlSht = xlWB.Worksheets[«Лист1»]; //или так xlSht = xlWB.ActiveSheet //активный лист iLastRow = xlSht.Cells[xlSht.Rows.Count, «A»].End[Excel.XlDirection.xlUp].Row; //последняя заполненная строка в столбце А iLastCol = xlSht.Cells[1, xlSht.Columns.Count].End[Excel.XlDirection.xlToLeft].Column; //последний заполненный столбец в 1-й строке |
Получаем список всех загруженных книг «листов» из файла
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//поиск файла Excel OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = false; ofd.DefaultExt = «*.xls;*.xlsx»; ofd.Filter = «Microsoft Excel (*.xls*)|*.xls*»; ofd.Title = «Выберите документ Excel»; if (ofd.ShowDialog() != DialogResult.OK) { MessageBox.Show(«Вы не выбрали файл для открытия», «Внимание», MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string xlFileName = ofd.FileName; //имя нашего Excel файла Excel.Workbook xlWB = ex.Workbooks.Open(xlFileName); ///загружаем список всех книг foreach (object item in xlWB.Sheets) { Excel.Worksheet sheet = (Excel.Worksheet)item; } |