Visual studio excel library

CcYAOu.png

##IronXL allows developers to Read, Generate and Edit Excel (and other Spreadsheet files) in .Net Applications & websites.

Ideal Workbook Manager — Generate, Read, and Edit Excel File with IronXL

If you ever felt Excel hinders your .NET office management skills, IronXL stands with you. This is why we created the #C Excel library that lets you, as a flourishing developer, read, generate, and edit Excel files in .NET applications and websites.

Along with creating a swift and natural solution in #C read excel file and other associated spreadsheet files, Iron Software prides itself in other success stories as well.

Load, Save, Sort, Style, and Much More with IronXL
Let’s get platform compatibilities out of the way; IronXL not only works smoothly in C#, VB.NET, MVC, ASP.NET projects for Websites, Console & Desktop applications but works with:

.NET Core 2 , 3 & 5
.NET Standard 2 & 3
.NET Framework 4.5 and above
Xamarin, SharePoint, Mono
Azure, AWS, Cloud hosting
Windows, Linux, Mac, Mobile
As an intuitive Excel API using C# & VB.NET, IronXL removes the need to install Microsoft Excel or Excel InterOp. Once you download IronXL’s #C library for free, access our virtually unlimited features, and equip yourself for your everyday tasks, for example, validation, conversion to a database, saving data from Web APIs, and modifying formulae within the spreadsheet.

Load, Read, and Edit Data
Supports multiple formats, import data from XLS/XLSX/CSV/TSV

Save and Export
Export worksheets to XLS/XLSX/CSV/TSV/JSON

System.Data Objects
Query, insert, update, and delete data with Excel Spreadsheets as System.Data.DataSet and System.Data.DataTable objects

Develop Formulas
Work with Excel formulas. Formulas are recalculated every time a sheet is edited.

Create Ranges
Easy to use WorkSheet[«A1:B10»] syntax. Combine and create ranges intuitively.

Sort the Data
Sort workbook range, column, and row.

Improve Aesthetics
Improve cell visual styles by modifying the font, size, background pattern, border, alignment, and number formats.

Using an Excel workbook seems underwhelming when you can create a dynamic workbook in #C using IronXL; the unlimited benefits include but are not limited to:

Service unique client requests
Create intuitive solutions to solve organizational problems
Circumvent Microsoft Office limitations
Create advanced Excel templates
Visually improved workbooks
In short, code to improve your spreadsheet, regardless of industry — whether it is accounting, financial systems, business digitization, enterprise content management or, data/reporting fields.

Move Ahead with IronXL

Visit our official site ironXL
Learn tutorial and deploy by a few lines of code here

Please visit this link dll download to learn more about IronXL.

Ready to Transition to IronXL?
Just as this article walks you through the benefits of the ability to create, modify, export, and read an excel file using #C; furthermore, our step-by-step reference tutorials to help you transition to IronXL effortlessly.

Yes, freeing yourself from MS Office dependencies is possible.

Download our Nuget package right away and benefit from a 30-day free trial key.

Are you a part of a larger team?

Begin developing, staging, and producing right away with our various lifetime licenses that include one year of 24/7 support and updates!

25BE6P.png

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

VB

CSharp

Worksheet object

Range object

object models [Office development in Visual Studio], Excel

object models [Office development in Visual Studio], Office

Workbook class

objects [Office development in Visual Studio], Office object models

Excel object model

Office object models

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 Sheetn 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.

C# Write to Excel [Without Using Interop] Code Example Tutorial

Follow step-by-step examples of how to create, open, and save Excel files with C#, and apply basic operations like getting sum, average, count, and more. IronXL.Excel is a stand alone .NET software library for reading a wide range of spreadsheet formats. It does not require Microsoft Excel to be installed, nor depend on Interop.

How to Write an Excel File in C#

  1. Download the Write Excel C# Library
  2. Create and open new CSV or XML Excel file as Excel workbook
  3. Save and export your Excel workbook
  4. Apply Advanced Operations in your multiple Excel worksheets
  5. Integrate with Excel Database

Overview

Use IronXL to Open and Write Excel Files

Open, write, save, and customize Excel files with the easy to use IronXL C# library.

Download a sample project from GitHub or use your own, and follow the tutorial.

  1. Install the IronXL Excel Library from NuGet or the DLL download
  2. Use the WorkBook.Load method to read any XLS, XLSX or CSV document.
  3. Get Cell values using intuitive syntax: sheet["A11"].DecimalValue

In this tutorial, we will walk you through:

  • Installing IronXL.Excel: how to install IronXL.Excel to an existing project.
  • Basic Operations: basic operation steps with Excel to Create or Open workbook, select sheet, select cell, and save the workbook
  • Advanced Sheet Operations: how to utilize different manipulation capabilities like adding headers or footers, mathematical operations files, and other features.

Open an Excel File : Quick Code

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-1.cs
using IronXL;

WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
IronXL.Range range = workSheet["A2:A8"];
decimal total = 0;

// iterate over range of cells
foreach (var cell in range)
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.RowIndex, cell.Value);
    if (cell.IsNumeric)
    {
        // Get decimal value to avoid floating numbers precision issue
        total += cell.DecimalValue;
    }
}

// Check formula evaluation
if (workSheet["A11"].DecimalValue == total)
{
    Console.WriteLine("Basic Test Passed");
}
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet
Private range As IronXL.Range = workSheet("A2:A8")
Private total As Decimal = 0

' iterate over range of cells
For Each cell In range
	Console.WriteLine("Cell {0} has value '{1}'", cell.RowIndex, cell.Value)
	If cell.IsNumeric Then
		' Get decimal value to avoid floating numbers precision issue
		total += cell.DecimalValue
	End If
Next cell

' Check formula evaluation
If workSheet("A11").DecimalValue = total Then
	Console.WriteLine("Basic Test Passed")
End If

VB   C#

Write and Save Changes to the Excel File : Quick Code

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-2.cs
workSheet["B1"].Value = 11.54;

// Save Changes
workBook.SaveAs("test.xlsx");
workSheet("B1").Value = 11.54

' Save Changes
workBook.SaveAs("test.xlsx")

VB   C#


Step 1

1. Install the IronXL C# Library FREE

C# NuGet Library for Excel

Install with NuGet

Install-Package IronXL.Excel

nuget.org/packages/IronXL.Excel/

or

C# Excel DLL

Download DLL

IronXL.Excel provides a flexible and powerful library for opening, reading, editing and saving Excel files in .NET. It can be installed and used on all of the .NET project types, like Windows applications, ASP.NET MVC and .NET Core Application.

Install the Excel Library to your Visual Studio Project with NuGet

The first step will be to install IronXL.Excel. To add IronXL.Excel library to the project, we have two ways : NuGet Package Manager or NuGet Package Manager Console.

To add IronXL.Excel library to our project using NuGet, we can do it using a visualized interface, NuGet Package Manager:

  1. Using mouse -> right click on project name -> Select manage NuGet Package

  2. From browse tab -> search for IronXL.Excel -> Install

  3. And we are done

Install Using NuGet Package Manager Console

  1. From tools -> NuGet Package Manager -> Package Manager Console

  2. Run command -> Install-Package IronXL.Excel -Version 2019.5.2

Manually Install with the DLL

You may also choose to manually install the DLL to your project or to your global assembly cache.

 PM > Install-Package  IronXL.Excel

How To Tutorials

2. Basic Operations: Create, Open, Save

2.1. Sample Project: HelloWorld Console Application

Create a HelloWorld Project

2.1.1. Open Visual Studio

2.1.2. Choose Create New Project

2.1.3. Choose Console App (.NET framework)

2.1.4. Give our sample the name “HelloWorld” and click create

2.1.5. Now we have console application created

2.1.6. Add IronXL.Excel => click install

2.1.7. Add our first few lines that reads 1st cell in 1st sheet in the Excel file, and print

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-3.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesHelloWorld.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
string cell = workSheet["A1"].StringValue;
Console.WriteLine(cell);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesHelloWorld.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim cell As String = workSheet("A1").StringValue
Console.WriteLine(cell)

VB   C#

2.2. Create a New Excel File

Create a new Excel file using IronXL

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-4.cs
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
workBook.Metadata.Title = "IronXL New File";
WorkSheet workSheet = workBook.CreateWorkSheet("1stWorkSheet");
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
workBook.Metadata.Title = "IronXL New File"
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("1stWorkSheet")
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed

VB   C#

2.3. Open (CSV, XML, JSON List) as Workbook

2.3.1. Open CSV file

2.3.2 Create a new text file and add to it a list of names and ages (see example) then save it as CSVList.csv

Your code snippet should look like this

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-5.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesCSVList.csv");
WorkSheet workSheet = workBook.WorkSheets.First();
string cell = workSheet["A1"].StringValue;
Console.WriteLine(cell);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesCSVList.csv")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim cell As String = workSheet("A1").StringValue
Console.WriteLine(cell)

VB   C#

2.3.3. Open XML File Create an XML file that contains a countries list: the root element “countries”, with children elements “country”, and each country has properties that define the country like code, continent, etc.

<?xml version="1.0" encoding="utf-8"?>
<countries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <country code="ae" handle="united-arab-emirates" continent="asia" iso="784">United Arab Emirates</country>
        <country code="gb" handle="united-kingdom" continent="europe" alt="England Scotland Wales GB UK Great Britain Britain Northern" boost="3" iso="826">United Kingdom</country>
        <country code="us" handle="united-states" continent="north america" alt="US America USA" boost="2" iso="840">United States</country>
        <country code="um" handle="united-states-minor-outlying-islands" continent="north america" iso="581">United States Minor Outlying Islands</country>
</countries>

HTML

2.3.4. Copy the following code snippet to open XML as a workbook

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-7.cs
DataSet xmldataset = new DataSet();
xmldataset.ReadXml($@"{Directory.GetCurrentDirectory()}FilesCountryList.xml");
WorkBook workBook = IronXL.WorkBook.Load(xmldataset);
WorkSheet workSheet = workBook.WorkSheets.First();
Dim xmldataset As New DataSet()
xmldataset.ReadXml($"{Directory.GetCurrentDirectory()}FilesCountryList.xml")
Dim workBook As WorkBook = IronXL.WorkBook.Load(xmldataset)
Dim workSheet As WorkSheet = workBook.WorkSheets.First()

VB   C#

2.3.5. Open JSON List as workbook Create JSON country list

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-8.cs
[
    {
        "name": "United Arab Emirates",
        "code": "AE"
    },
    {
        "name": "United Kingdom",
        "code": "GB"
    },
    {
        "name": "United States",
        "code": "US"
    },
    {
        "name": "United States Minor Outlying Islands",
        "code": "UM"
    }
]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'[{ "name": "United Arab Emirates", "code": "AE" }, { "name": "United Kingdom", "code": "GB" }, { "name": "United States", "code": "US" }, { "name": "United States Minor Outlying Islands", "code": "UM" }]

VB   C#

2.3.6. Create a country model that will map to JSON

Here is the class code snippet

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-9.cs
public class CountryModel
    {
        public string name { get; set; }
        public string code { get; set; }
    }
Public Class CountryModel
		Public Property name() As String
		Public Property code() As String
End Class

VB   C#

2.3.8. Add Newtonsoft library to convert JSON to the list of country models

2.3.9 To convert the list to dataset, we have to create a new extension for the list. Add extension class with the name “ListConvertExtension”

Then add this code snippet

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-10.cs
public static class ListConvertExtension
    {
        public static DataSet ToDataSet<T>(this IList<T> list)
        {
            Type elementType = typeof(T);
            DataSet ds = new DataSet();
            DataTable t = new DataTable();
            ds.Tables.Add(t);
            //add a column to table for each public property on T
            foreach (var propInfo in elementType.GetProperties())
            {
                Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
                t.Columns.Add(propInfo.Name, ColType);
            }
            //go through each property on T and add each value to the table
            foreach (T item in list)
            {
                DataRow row = t.NewRow();
                foreach (var propInfo in elementType.GetProperties())
                {
                    row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                }
                t.Rows.Add(row);
            }
            return ds;
        }
    }
Public Module ListConvertExtension
		<System.Runtime.CompilerServices.Extension> _
		Public Function ToDataSet(Of T)(ByVal list As IList(Of T)) As DataSet
			Dim elementType As Type = GetType(T)
			Dim ds As New DataSet()
'INSTANT VB NOTE: The variable t was renamed since Visual Basic does not allow local variables with the same name as method-level generic type parameters:
			Dim t_Conflict As New DataTable()
			ds.Tables.Add(t_Conflict)
			'add a column to table for each public property on T
			For Each propInfo In elementType.GetProperties()
				Dim ColType As Type = If(Nullable.GetUnderlyingType(propInfo.PropertyType), propInfo.PropertyType)
				t_Conflict.Columns.Add(propInfo.Name, ColType)
			Next propInfo
			'go through each property on T and add each value to the table
			For Each item As T In list
				Dim row As DataRow = t_Conflict.NewRow()
				For Each propInfo In elementType.GetProperties()
					row(propInfo.Name) = If(propInfo.GetValue(item, Nothing), DBNull.Value)
				Next propInfo
				t_Conflict.Rows.Add(row)
			Next item
			Return ds
		End Function
End Module

VB   C#

And finally load this dataset as a workbook

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-11.cs
StreamReader jsonFile = new StreamReader($@"{Directory.GetCurrentDirectory()}FilesCountriesList.json");
var countryList = Newtonsoft.Json.JsonConvert.DeserializeObject<CountryModel[]>(jsonFile.ReadToEnd());
var xmldataset = countryList.ToDataSet();
WorkBook workBook = IronXL.WorkBook.Load(xmldataset);
WorkSheet workSheet = workBook.WorkSheets.First();
Dim jsonFile As New StreamReader($"{Directory.GetCurrentDirectory()}FilesCountriesList.json")
Dim countryList = Newtonsoft.Json.JsonConvert.DeserializeObject(Of CountryModel())(jsonFile.ReadToEnd())
Dim xmldataset = countryList.ToDataSet()
Dim workBook As WorkBook = IronXL.WorkBook.Load(xmldataset)
Dim workSheet As WorkSheet = workBook.WorkSheets.First()

VB   C#

2.4. Save and Export

We can save or export the Excel file to multiple file formats like (“.xlsx”,”.csv”,”.html”) using one of the following commands.

2.4.1. Save to “.xlsx” To Save to “.xlsx” use saveAs function

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-12.cs
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
workBook.Metadata.Title = "IronXL New File";

WorkSheet workSheet = workBook.CreateWorkSheet("1stWorkSheet");
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;

workBook.SaveAs($@"{Directory.GetCurrentDirectory()}FilesHelloWorld.xlsx");
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
workBook.Metadata.Title = "IronXL New File"

Dim workSheet As WorkSheet = workBook.CreateWorkSheet("1stWorkSheet")
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed

workBook.SaveAs($"{Directory.GetCurrentDirectory()}FilesHelloWorld.xlsx")

VB   C#

2.4.2. Save to csv “.csv” To save to “.csv” we can use SaveAsCsv and pass to it 2 parameters 1st parameter the file name and path the 2nd parameter is the delimiter like (“,” or “|” or “:”)

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-13.cs
workBook.SaveAsCsv($@"{Directory.GetCurrentDirectory()}FilesHelloWorld.csv", delimiter: "|");
workBook.SaveAsCsv($"{Directory.GetCurrentDirectory()}FilesHelloWorld.csv", delimiter:= "|")

VB   C#

2.4.3. Save to JSON “.json” To save to Json “.json” use SaveAsJson as follow

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-14.cs
workBook.SaveAsJson($@"{Directory.GetCurrentDirectory()}FilesHelloWorldJSON.json");
workBook.SaveAsJson($"{Directory.GetCurrentDirectory()}FilesHelloWorldJSON.json")

VB   C#

The result file should look like this

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-15.cs
[
    [
        "Hello World"
    ],
    [
        ""
    ]
]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'[["Hello World"], [""]]

VB   C#

2.4.4. Save to XML “.xml” To save to xml use SaveAsXml as follow

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-16.cs
workBook.SaveAsXml($@"{Directory.GetCurrentDirectory()}FilesHelloWorldXML.XML");
workBook.SaveAsXml($"{Directory.GetCurrentDirectory()}FilesHelloWorldXML.XML")

VB   C#

Result should be like this

<?xml version="1.0" standalone="yes"?>
<_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Hello World</Column1>
  </_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </_x0031_stWorkSheet>
</_x0031_stWorkSheet>

HTML


3. Advanced Operations: Sum, Avg, Count, etc.

Let’s apply common Excel functions like SUM, AVG, Count and see each code snippet.

3.1. Sum Example

Let’s find the sum for this list. I created an Excel file and named it “Sum.xlsx” and added this list of numbers manually

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-18.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal sum = workSheet["A2:A4"].Sum();
Console.WriteLine(sum);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim sum As Decimal = workSheet("A2:A4").Sum()
Console.WriteLine(sum)

VB   C#

3.2. Avg Example

Using the same file, we can get the average:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-19.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal avg = workSheet["A2:A4"].Avg();
Console.WriteLine(avg);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim avg As Decimal = workSheet("A2:A4").Avg()
Console.WriteLine(avg)

VB   C#

3.3. Count Example

Using the same file, we can also get the number of elements in a sequence:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-20.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal count = workSheet["A2:A4"].Count();
Console.WriteLine(count);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim count As Decimal = workSheet("A2:A4").Count()
Console.WriteLine(count)

VB   C#

3.4. Max Example

Using the same file, we can get the max value of range of cells:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-21.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal max = workSheet["A2:A4"].Max();
Console.WriteLine(max);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim max As Decimal = workSheet("A2:A4").Max()
Console.WriteLine(max)

VB   C#

– We can apply the transform function to the result of max function:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-22.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
bool max2 = workSheet["A1:A4"].Max(c => c.IsFormula);
Console.WriteLine(max2);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim max2 As Boolean = workSheet("A1:A4").Max(Function(c) c.IsFormula)
Console.WriteLine(max2)

VB   C#

This example writes “false” in the console.

3.5. Min Example

Using the same file, we can get the min value of range of cells:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-23.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal min = workSheet["A1:A4"].Min();
Console.WriteLine(min);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim min As Decimal = workSheet("A1:A4").Min()
Console.WriteLine(min)

VB   C#

3.6. Order Cells Example

Using the same file, we can order cells by ascending or descending:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-24.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
workSheet["A1:A4"].SortAscending();
// workSheet["A1:A4"].SortDescending(); to order descending
workBook.SaveAs("SortedSheet.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
workSheet("A1:A4").SortAscending()
' workSheet["A1:A4"].SortDescending(); to order descending
workBook.SaveAs("SortedSheet.xlsx")

VB   C#

3.7. If Condition Example

Using the same file, we can use the Formula property to set or get a cell’s formula:

3.7.1. Save to XML “.xml”

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-25.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesSum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
int i = 1;
foreach (var cell in workSheet["B1:B4"])
{
    cell.Formula = "=IF(A" + i + ">=20," Pass" ," Fail" )";
    i++;
}
workBook.SaveAs($@"{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesSum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim i As Integer = 1
For Each cell In workSheet("B1:B4")
	cell.Formula = "=IF(A" & i & ">=20,"" Pass"" ,"" Fail"" )"
	i += 1
Next cell
workBook.SaveAs($"{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx")

VB   C#

7.2. Using the generated file from the previous example, we can get the Cell’s Formula:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-26.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
foreach (var cell in workSheet["B1:B4"])
{
    Console.WriteLine(cell.Formula);
}
Console.ReadKey();
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
For Each cell In workSheet("B1:B4")
	Console.WriteLine(cell.Formula)
Next cell
Console.ReadKey()

VB   C#

3.8. Trim Example

To apply trim function (to eliminate all extra spaces in cells), I added this column to the sum.xlsx file

And use this code

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-27.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
int i = 1;
foreach (var cell in workSheet["f1:f4"])
{
    cell.Formula = "=trim(D" + i + ")";
    i++;
}
workBook.SaveAs("editedFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim i As Integer = 1
For Each cell In workSheet("f1:f4")
	cell.Formula = "=trim(D" & i & ")"
	i += 1
Next cell
workBook.SaveAs("editedFile.xlsx")

VB   C#

Thus, you can apply formulas in the same way.


4. Working with Multisheet Workbooks

We will go through how to work with workbook that have more than one sheet.

4.1. Read Data from Multiple Sheets in the Same Workbook

I created an xlsx file that contains two sheets: “Sheet1”,” Sheet2”

Until now we used WorkSheets.First() to work with the first sheet. In this example we will specify the sheet name and work with it

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-28.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilestestFile.xlsx");
WorkSheet workSheet = workBook.GetWorkSheet("Sheet2");
var range = workSheet["A2:D2"];
foreach (var cell in range)
{
    Console.WriteLine(cell.Text);
}
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilestestFile.xlsx")
Dim workSheet As WorkSheet = workBook.GetWorkSheet("Sheet2")
Dim range = workSheet("A2:D2")
For Each cell In range
	Console.WriteLine(cell.Text)
Next cell

VB   C#

4.2. Add New Sheet to a Workbook

We can also add new sheet to a workbook:

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-29.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilestestFile.xlsx");
WorkSheet workSheet = workBook.CreateWorkSheet("new_sheet");
workSheet["A1"].Value = "Hello World";
workBook.SaveAs(@"F:MY WORKIronPackageXl tutorialnewFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilestestFile.xlsx")
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("new_sheet")
workSheet("A1").Value = "Hello World"
workBook.SaveAs("F:MY WORKIronPackageXl tutorialnewFile.xlsx")

VB   C#


5. Integrate with Excel Database

Let’s see how to export/import data to/from Database.

I created the «TestDb» database containing a Country table with two columns: Id (int, identity), CountryName(string)

5.1. Fill Excel sheet with Data from Database

Here we will create a new sheet and fill it with data from the Country Table

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-30.cs
TestDbEntities dbContext = new TestDbEntities();
var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilestestFile.xlsx");
WorkSheet sheet = workbook.CreateWorkSheet("FromDb");
List<Country> countryList = dbContext.Countries.ToList();
sheet.SetCellValue(0, 0, "Id");
sheet.SetCellValue(0, 1, "Country Name");
int row = 1;
foreach (var item in countryList)
{
    sheet.SetCellValue(row, 0, item.id);
    sheet.SetCellValue(row, 1, item.CountryName);
    row++;
}
workbook.SaveAs("FilledFile.xlsx");
Dim dbContext As New TestDbEntities()
Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilestestFile.xlsx")
Dim sheet As WorkSheet = workbook.CreateWorkSheet("FromDb")
Dim countryList As List(Of Country) = dbContext.Countries.ToList()
sheet.SetCellValue(0, 0, "Id")
sheet.SetCellValue(0, 1, "Country Name")
Dim row As Integer = 1
For Each item In countryList
	sheet.SetCellValue(row, 0, item.id)
	sheet.SetCellValue(row, 1, item.CountryName)
	row += 1
Next item
workbook.SaveAs("FilledFile.xlsx")

VB   C#

5.2. Fill Database with Data from Excel Sheet

Insert the data to the Country table in TestDb Database

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-31.cs
TestDbEntities dbContext = new TestDbEntities();
var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}FilestestFile.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet3");
System.Data.DataTable dataTable = sheet.ToDataTable(true);
foreach (DataRow row in dataTable.Rows)
{
    Country c = new Country();
    c.CountryName = row[1].ToString();
    dbContext.Countries.Add(c);
}
dbContext.SaveChanges();
Dim dbContext As New TestDbEntities()
Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}FilestestFile.xlsx")
Dim sheet As WorkSheet = workbook.GetWorkSheet("Sheet3")
Dim dataTable As System.Data.DataTable = sheet.ToDataTable(True)
For Each row As DataRow In dataTable.Rows
	Dim c As New Country()
	c.CountryName = row(1).ToString()
	dbContext.Countries.Add(c)
Next row
dbContext.SaveChanges()

VB   C#


Further Reading

To learn more about working with IronXL, you may wish to look at the other tutorials within this section, and also the examples on our homepage, which most developers find enough to get them started.

Our API Reference contains specific references to the WorkBook class.


Tutorial Quick Access

Download this Tutorial as C# Source Code

The full free C# for Excel Source Code for this tutorial is available to download as a zipped Visual Studio 2017 project file.

Download

Explore this Tutorial on GitHub

The source code for this project is available in C# and VB.NET on GitHub.

Use this code as an easy way to get up and running in just a few minutes. The project is saved as a Microsoft Visual Studio 2017 project, but is compatible with any .NET IDE.

How to Open and Write Excel File in C# on GitHub

API Reference for IronXL

Explore the API Reference for IronXL, outlining the details of all of IronXL’s features, namespaces, classes, methods fields and enums.

View the API Reference

The .NET Excel library can revolutionise bring data into and out of  web applications and business systems.

Elijah Williams

Product Development Engineer

Elijah is an engineer on a Development and Testing team responsible for a large corporate financial reporting system. Elijah has been an early adopter of the IronXL Library, featuring it in the core of their Excel reporting interface.

Время на прочтение
7 мин

Количество просмотров 69K

В современном мире разработки приложений нередко встает необходимость работы с Excel документами. Чаще всего это разного рода отчеты, но иногда xls/x файлы используются в качестве хранилища данных. Например, если пользователь должен иметь возможность загрузить данные в приложение или выгрузить, в человеко-читаемом виде, Excel де-факто является стандартом. Относительно дружелюбный интерфейс, прозрачная структура, в купе с его распространенностью… трудно навскидку назвать решение лучше.

Однако, у многих Excel до сих пор ассоциируется с чем-то тяжелым, неповоротливым и сложным. Давайте посмотрим, как мы — обычные C# разработчики, можем легко сформировать простой Excel документ, на примере табличного отчета.

Историческая справка

Времена, когда доминировал проприетарный формат .xls(Excel Binary File Format) давно прошли и сейчас мы имеем только .xlsx(Excel Workbook), в рамках Office Open XML. Последний представляет собой обычный .zip архив с XML файлами. Не будем углубляться в его структуру, я искренне надеюсь что вам это никогда не понадобится.

На github, и не только, можно найти ряд библиотек, бесплатных и не только. Пожалуй самой популярной является EPPlus. До определенной степени, она довольно хорошо отражает концепцию Excel, именно по этому я всегда использую EPPlus. Версия 4 полностью бесплатна, начиная с 5‐й версии вам потребуется приобрести лицензию для коммерческого использования.

Задача

Итак, предположим, продукт-мэнеджеру ударила в голову идея того, что возможность выгружать некий отчет в формате Excel увеличит кол-во пользователей на 100500%. Проджет-менеджер решает выкатить эту киллер-фичу как хотфикс прямо сегодня — ведь работы всего на пару часов.

Сам по себе, отчет содержит краткое описание компании и историю изменения некоторых экономических показателей. Для простоты все свойства компании — строки. Экономические показатели — большие целые числа и числа с плавающей точкой, а также даты. Предположим, что где-то в недрах микросервисного backend-да есть сервис-генератор подобных отчетов, например по id компании. Однако, поскольку id нет смысла выводить пользователю, идентификатор отсутствует в самой модели отчета.

Аналитик, в свою очередь, выдает задачу с феноменально точным описанием — «Сгенерировать excel отчет на базе данных MarketReport». Что ж, для нашего примера, создадим заглушку — генератор фейковых данных:

Первый запуск

Подключим EPPlus версии 4.5.3.3 и создадим базовую обвязку для будущего генератора.

Сердцем генератора будет метод Generate. ExcelPackage это модель документа, через которую мы и будем осуществлять все взаимодействия с ним. Также имеется конструктор для передачи пути к файлу или потока.

В методе main создается генератор отчетов, а также генератор Excel файлов. Далее полученный файл просто записывается на диск.

При попытке запустить приложение, получаем exception:InvalidOperationException: The workbook must contain at least one worksheet

Все правильно, Excel документ не может существовать без страниц, должна быть хотя бы одна. Добавляем ее, все интуитивно понятно:

var sheet = package.Workbook.Worksheets    
		.Add("Market Report");

Запускаем снова и… вот оно! Теперь наше приложение генерирует документ и, хотя там еще ничего нет, он уже весит 2,5KB — значит мы работаем с Excel правильно и все идет как надо.

Вывод данных

Давайте выведем основную информацию по компании в шапку. Для доступа к конкретной ячейки объект Cells на странице пакета снабжен удобным индексатором. При этом, до конкретной ячейки можно достучаться как через номер строки и столбца, так и по привычному всем буквенно-числовому коду:

sheet.Cells["B2"].Value = "Company:";
sheet.Cells[2, 3].Value = report.Company.Name;

Полный код вывода шапки.

sheet.Cells["B2"].Value = "Company:";
sheet.Cells[2, 3].Value = report.Company.Name;
sheet.Cells["B3"].Value = "Location:";
sheet.Cells["C3"].Value = $"{report.Company.Address}, " +
  												$"{report.Company.City}, " +                          
  												$"{report.Company.Country}";
sheet.Cells["B4"].Value = "Sector:";
sheet.Cells["C4"].Value = report.Company.Sector;
sheet.Cells["B5"].Value = report.Company.Description;

Для вывода исторических данных понадобится как минимум шапка таблицы и цикл по массиву History:

sheet.Cells[8, 2, 8, 4].LoadFromArrays(new object[][]{ new []{"Capitalization", "SharePrice", "Date"} });
var row = 9;
var column = 2;
foreach (var item in report.History)
{
  sheet.Cells[row, column].Value = item.Capitalization;
  sheet.Cells[row, column + 1].Value = item.SharePrice;
  sheet.Cells[row, column + 2].Value = item.Date;    
  row++;
}

Предлагаю обратить внимание на метод LoadFromArrays, который заполняет диапазон ячеек рваным(зубчатым) массивом. Здесь мы можем видеть, что типизация теряется и передавая массив object мы ожидаем что EPPlus в конечном итоге использует ToString, чтобы записать переданное в ячейки.

Стилизация

Если вы прямо сейчас откроете документ, то вы возможно увидите не то, что хотелось бы отдать в продакшн в пятницу вечером.

Как это выглядит

Во-первых, шапка никак не выделяется, во-вторых таблица не имеет границ… выравнивание пляшет, даты отображаются магическими числами, а капитализация «уходит в какую-то математику» — как это прокомментировал аналитик.

Да, на все эти красивости у нас уйдет больше года кода, чем на сам вывод данных, и, в конечном тоге, получившаяся каша из логики вывода данных и разметки заставит некоторых усомниться в их компетентности… но, мы же backend разработчики, так давайте сверстаем Excel Sheet!

Размер ячеек

Из коробки у нас есть возможность сделать автофит а так же вручную выставить ширину в соответствии с нашей ситуацией. А ситуация у нас не самая хорошая — по задумке аналитика в шапке у ячеек должен быть автофит, а у ячеек таблицы — тоже автофит. Так в чем же подвох?

Если вы когда-нибудь до этого открывали Excel, то возможно знаете, что ширина ячеек не может отличаться в рамках столбца и автофит будет по самому широкому контенту ячейки. Однако, простые вещи бывает нетак то просто объяснить… Но если вы справитесь, то вот как это будет выглядеть в коде:

sheet.Cells[1, 1, row, column + 2].AutoFitColumns();
sheet.Column(2).Width = 14;
sheet.Column(3).Width = 12;

Формат данных

Как и большая часть стиля ячейки, он задается через одноименное свойство Style. Обратите внимание на вычисление 3-го аргумента индексатора. Это звоночек некачественного кода, но к этому мы вернемся в позже…

sheet.Cells[9, 4, 9 + report.History.Length, 4].Style.Numberformat.Format = "yyyy";
sheet.Cells[9, 2, 9 + report.History.Length, 2].Style.Numberformat.Format =  "### ### ### ##0";

Выравнивание

Его можно задать как на ячейке, так и на диапазоне. На самом деле, для EPPlus, это одна и та же сущность — некий ExcelRange, описывающий диапазон ячеек, в том числе и со всего 1 ячейкой.

sheet.Column(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
sheet.Cells[8, 3, 8 + report.History.Length, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

Стиль текста

Также легко задается, используя Style.Font, кстати, здесь, на 2-й строчке, мы впервые указываем диапазон так, как привыкли его видеть пользователи Excel:

sheet.Cells[8, 2, 8, 4].Style.Font.Bold = true;
sheet.Cells["B2:C4"].Style.Font.Bold = true;

Границы

Задаем стиль линии, а также ее толщину. К этому моменту от кол-ва магических чисел-параметров индексатора уже рябит в глазах, но мы уже на финишной прямой… не так ли?

sheet.Cells[8, 2, 8 + report.History.Length, 4].Style.Border.BorderAround(ExcelBorderStyle.Double);
sheet.Cells[8, 2, 8, 4].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

График

«Ну что за отчет без графиков, верно, Карл?» — ловко подметит специалист по тестированию, и не важно, что этого не было в ТЗ а на часах уже половина 9-го…

Хотя график как сущность сам по себе сложнее таблиц и с графиками мы не работаем каждый день, EPPlus предоставляет довольно понятный API. Давайте добавим простейший график, отражающий рост капитализации:

var capitalizationChart = sheet.Drawings.AddChart("FindingsChart", OfficeOpenXml.Drawing.Chart.eChartType.Line);
capitalizationChart.Title.Text = "Capitalization";
capitalizationChart.SetPosition(7, 0, 5, 0);
capitalizationChart.SetSize(800, 400);
var capitalizationData = (ExcelChartSerie)(capitalizationChart.Series.Add(sheet.Cells["B9:B28"], sheet.Cells["D9:D28"]));
capitalizationData.Header = report.Company.Currency;

Еще, может понадобиться защитить страницу от редактирования:

sheet.Protection.IsProtected = true;

На этом все, репозиторий с рабочим приложением находится здесь.

Заключение

О чем говорит финальная версия метода Generate?

public byte[] Generate(MarketReport report)
{    
  var package = new ExcelPackage();    
  
  var sheet = package.Workbook.Worksheets        
    	.Add("Market Report");      
  
  sheet.Cells["B2"].Value = "Company:";    
  sheet.Cells[2, 3].Value = report.Company.Name;    
  sheet.Cells["B3"].Value = "Location:";    
  sheet.Cells["C3"].Value = $"{report.Company.Address}, " +
    												$"{report.Company.City}, " +                             
    												$"{report.Company.Country}";    
  sheet.Cells["B4"].Value = "Sector:";    
  sheet.Cells["C4"].Value = report.Company.Sector;    
  sheet.Cells["B5"].Value = report.Company.Description;    
  
  sheet.Cells[8, 2, 8, 4].LoadFromArrays(new object[][]{ new []{"Capitalization", "SharePrice", "Date"} });    
  var row = 9;    
  var column = 2;    
  foreach (var item in report.History)    
  {        
    	sheet.Cells[row, column].Value = item.Capitalization;        
   		sheet.Cells[row, column + 1].Value = item.SharePrice;        
   		sheet.Cells[row, column + 2].Value = item.Date;        
    	row++;    
  }    
  
  sheet.Cells[1, 1, row, column + 2].AutoFitColumns();    
  sheet.Column(2).Width = 14;    
  sheet.Column(3).Width = 12;        
  
  sheet.Cells[9, 4, 9+ report.History.Length, 4].Style.Numberformat.Format = "yyyy";    
  sheet.Cells[9, 2, 9+ report.History.Length, 2].Style.Numberformat.Format =  "### ### ### ##0";    
  
  sheet.Column(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;    
  sheet.Cells[8, 3, 8 + report.History.Length, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;    
  sheet.Column(4).Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;    
  
  sheet.Cells[8, 2, 8, 4].Style.Font.Bold = true;    
  sheet.Cells["B2:C4"].Style.Font.Bold = true;
  
  sheet.Cells[8, 2, 8 + report.History.Length, 4].Style.Border.BorderAround(ExcelBorderStyle.Double);    
  sheet.Cells[8, 2, 8, 4].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;     
  
  var capitalizationChart = sheet.Drawings.AddChart("FindingsChart", OfficeOpenXml.Drawing.Chart.eChartType.Line);    
  capitalizationChart.Title.Text = "Capitalization";    
  capitalizationChart.SetPosition(7, 0, 5, 0);    
  capitalizationChart.SetSize(800, 400);    
  var capitalizationData = (ExcelChartSerie)(capitalizationChart.Series.Add(sheet.Cells["B9:B28"], sheet.Cells["D9:D28"]));    
  capitalizationData.Header = report.Company.Currency;       
  
  sheet.Protection.IsProtected = true;    
  
  return package.GetAsByteArray();
}

Во-первых, прежде всего, о том, что мы успешно справились с задачей, а именно, сгенерировали свой первый Excel отчет, поработали со стилями и даже решили пару попутных проблем.

Во-вторых, возможно имеет смысл искать новою работу, но, забегая вперед, я бы с этим не спешил… Если данная публикация наберет 1+ просмотров, то во второй части мы поговорим о том, как можно отделить стилизацию от логики заполнения данными, упростить манипуляции над ячейками и в целом сделаем код боле поддерживаемым.

In this tutorial I will show you how to create an Excel file using the C# programming language. This tutorial consists of a step-by-step guide specially designed for beginners and intermediate developers. Experts can skip the “project creation” section and jump directly to the “code” section. I will use the IronXL Library to create Excel files.

We will cover the following topics:

  • What is an Excel File?
  • What is IronXL?
  • A Step-by-Step Guide to Creating Excel Files
  • Step 1: Create a Visual Studio Project
  • Step 2: Install the NuGet Package
  • Step 3: Create an Excel Workbook
  • Step 4: Set a Default Worksheet
  • Step 5: Save the Workbook
  • Step 6: Set Cell Values
  • Set Cell Values Manually
  • Set Cell Values Dynamically
  • Set Cell Values from the Database
  • Summary

What is an Excel File?

Excel is a spreadsheet application developed and published by Microsoft. It is part of the Microsoft Office suite of productivity software.
Excel is a tool for both organizing data and making calculations with it. The software can analyze data, calculate statistics, generate pivot tables, and represent data as charts or graphs.
For example, you could create an Excel spreadsheet that calculates a monthly budget, tracks associated expenses, and interactively sorts the data by various criteria.
Unlike a word processor, such as Microsoft Word, Excel organizes data in columns and rows. Rows and columns intersect at a space called a cell. Each cell contains data, such as text, numerical values, or formulas.

What is IronXL?

IronXL is an intuitive C# & VB Excel API that allows you to read, edit and create Excel spreadsheet files in .NET with lightning-fast performance. There is no need to install MS Office or even Excel Interop. This library can also be used for manipulating Excel documents.
IronXL fully supports .NET Core, .NET Framework, Xamarin, Mobile, Linux, MacOS and Azure.
Image description

A Step-by-Step Guide to Creating Excel Files

Firstly, we have to create a new Visual Studio Project. I will use the Console Application template for the demonstration. You can use any template that best suits your requirements.
You may also use a current project that would benefit from the capacity to create Excel files.

Step1: Create a Visual Studio Project

Open Microsoft Visual Studio 2019 or any other version. However, the latest version is recommended. Click on “Create New Project”. Select the C# Console Application for the application template. Click on the “Next” button.
Assign a name to your project. I have named mine «Excel Tutorial». You can select any name you wish. Click the “Next” button, and set the target framework. I have set my target framework to «.Net 5.0», the latest and most stable version. Click the “Create” button, and a new project will be created for you.

(adsbygoogle = window.adsbygoogle || []).push({});

Step 2: Install the NuGet Package in Visual Studio

Our next step is to install the IronXL NuGet Package for our project. Click on “Tools” on the menu bar. A new drop-down menu will appear. Click on «NuGet Package Manager» and then «Manage Nuget Packages for Solution», as shown below.
Image description
Click on “Browse” and search for IronXL in the search bar.
Image description
Click on “IronXL.Excel” and press the “Installed” button. This will install IronXL in your project. Now you are free to use any of its functions in your project.
Now that the IronXL Library has been installed, let’s go to the next step.

Step 3: Create an Excel Workbook

Firstly, add the namespace of IronXL into your project.

using IronXL;

Enter fullscreen mode

Exit fullscreen mode

It could not be easier to create a new Excel Workbook using IronXL! We need just one line of code. Yes, really!

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

Enter fullscreen mode

Exit fullscreen mode

Both the XLS (older Excel file versions) and XLSX (current and newer file versions) file formats can be created with IronXL.

Step 4: Set a Default Worksheet

Let’s create an Excel spreadsheet. I have just created one. You can create as many Excel spreadsheets as you need.

var sheet = workbook.CreateWorkSheet("Result Sheet");

Enter fullscreen mode

Exit fullscreen mode

«Sheet» in the above code snippet represents the worksheet, and you can use it to set cell values and almost everything else Excel can do.
If you are confused about the difference between a Workbook and a Worksheet, let me explain: a Workbook contains Worksheets. This means that you can add as many Worksheets as you like into one Workbook. I will explain how to do this in a later article. A Worksheet contains rows and columns. The intersection of a row and a column is called a cell, and these cells are what we manipulate whilst working with Excel.

Step 5: Save the Workbook

To save the xlsx format Workbook, use the following code:

workbook.SaveAs("Budget.xlsx");

Enter fullscreen mode

Exit fullscreen mode

Run the program to see the output.

Output File

This program will create a new workbook. You can find it in your project bin folder. You can also specify the path with the “Save As” function. Open your Excel document with Microsoft Excel. Below is the Excel worksheet we have just created.
Image description

Step 6: Setting Cell Values

Now that our workbook is created and saved, let’s add some data to the cell.

Setting Cell Values Manually:

To set cell values manually, you simply indicate which cell you are working with and set its value, as in the following example:

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
            var sheet = workbook.CreateWorkSheet("Result Sheet");
// Set Cell Values Manually
            sheet["A1"].Value = "Object Oriented Programming";
            sheet["B1"].Value = "Data Structure";
            sheet["C1"].Value = "Database Management System";
            sheet["D1"].Value = "Agile Development";
            sheet["E1"].Value = "Software Design and Architecture";
            sheet["F1"].Value = "Software Requirement Engineering";
            sheet["G1"].Value = "Computer Programming";
            sheet["H1"].Value = "Software Project Management";
            sheet["I1"].Value = "Software Construction";
            sheet["J1"].Value = "Software Quality Engineering";
            sheet["K1"].Value = "Software ReEngineering";
            sheet["L1"].Value = "Advance Database Management System";
// Save Workbook
            workbook.SaveAs("Result Sheet.xlsx");

Enter fullscreen mode

Exit fullscreen mode

Here, I have populated Columns A to L, and the first row of each to the names of various courses related to software engineering.
Run the program to see the output:

Output File

Image description

Setting Cell Values Dynamically

To set values dynamically we employ instructions that are very similar to those under the previous heading. The advantage here is that you do not have to hard-code the cell location. In the next code example, you will create a new random object to create random numbers, and then make use of a loop to iterate through the range of cells you’d like to populate with values.

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
            var sheet = workbook.CreateWorkSheet("Result Sheet");
            /**
            Set Cell Value Dynamically
            **/
            Random r = new Random();
            for (int i = 2; i <= 11; i++)
            {
                sheet["A" + i].Value = r.Next(1, 100);
                sheet["B" + i].Value = r.Next(1, 100);
                sheet["C" + i].Value = r.Next(1, 100);
                sheet["D" + i].Value = r.Next(1, 100);
                sheet["E" + i].Value = r.Next(1, 100);
                sheet["F" + i].Value = r.Next(1, 100);
                sheet["G" + i].Value = r.Next(1, 100);
                sheet["H" + i].Value = r.Next(1, 100);
                sheet["I" + i].Value = r.Next(1, 100);
                sheet["J" + i].Value = r.Next(1, 100);
                sheet["K" + i].Value = r.Next(1, 100);
                sheet["L" + i].Value = r.Next(1, 100);
            }
            // Save Workbook
            workbook.SaveAs("Result Sheet.xlsx");
        }

Enter fullscreen mode

Exit fullscreen mode

Every cell from A2 to L11 contains a unique value that was randomly generated.
Let’s run the program. It will create an excel file for us. Open this with Microsoft Excel to see the output.

Output

Image description
Talking about dynamic values, how about learning how to dynamically add data into cells directly from a database? The next code snippet quickly shows how this is done, assuming you have set up your database connections correctly.

Adding Data Directly from a Database

I will get the data from the table and assign those values to the cells of my spreadsheet. Here is a snapshot of my “Marks” table:
Image description
I will get the data from that tables and assign those values to the cells of my spreadsheet. Here is the snapshot of my Marks Table.

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
            var sheet = workbook.CreateWorkSheet("Result Sheet");
            //Create database objects to populate data from database
            string contring;
            string sql;
            DataSet ds = new DataSet("ResultSet");
            SqlConnection con;
            SqlDataAdapter da;
            //Set Database Connection string
            contring = @"data source = DESKTOP-FEP5MVSSQLEXPRESS; Initial Catalog = Result; Integrated Security = True; ";
            //SQL Query to obtain data
            sql = "SELECT [Data Structure],[Computer Programming] , [Agile Development] , [Software ReEngineering] , [Software Construction]  FROM Marks";
            //Open Connection & Fill DataSet
            con = new SqlConnection(contring);
            da = new SqlDataAdapter(sql, con);
            con.Open();
            da.Fill(ds);
            //Loop through Column
            foreach (DataTable table in ds.Tables)
            {
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    sheet["A1"].Value = table.Columns[j].ToString();
                    sheet["B1"].Value = table.Columns[j].ToString();
                    sheet["C1"].Value = table.Columns[j].ToString();
                    sheet["D1"].Value = table.Columns[j].ToString();
                    sheet["E1"].Value = table.Columns[j].ToString();
                }
            }

            //Loop through contents of dataset
            foreach (DataTable table in ds.Tables)
            {
                for (int j = 0; j < table.Rows.Count; j++)
                {
                    sheet["A" + (j + 2)].Value = table.Rows[j]["Data Structure"].ToString();
                    sheet["B" + (j + 2)].Value = table.Rows[j]["Computer Programming"].ToString();
                    sheet["C" + (j + 2)].Value = table.Rows[j]["Agile Development"].ToString();
                    sheet["D" + (j + 2)].Value = table.Rows[j]["Software ReEngineering"].ToString();
                    sheet["E" + (j + 2)].Value = table.Rows[j]["Software Construction"].ToString();
                }
            }
            // Save Workbook
            workbook.SaveAs("Result Sheet.xlsx");
        }

Enter fullscreen mode

Exit fullscreen mode

In the above code, I first set the connection string of my database, and then I read the data from the table. Next, I assigned the column name to the Excel spreadsheet in the first loop, and values of the table in the second loop.
You simply have to set the value property of the particular cell to the field name, so that it can be entered into the cell.

Output File

Let’s run the program. It will create an Excel file for us. Open this with Microsoft Excel to see the output.
Image description

Summary

IronXL allow us to generate new Excel files in C#, create new worksheets inside them, set font sizes, use formulas and much more. There are too many functions and details to describe here. For more detailed information, please click here.

Iron software provides other libraries such as IronPdf for creating Pdf documents, Iron Barcode for generating, reading and manipulating barcode, and so forth. If you purchase the complete Iron suite, you will be eligible to receive all 5 products for the price of just two. For more details, please click here.

I hope this article was helpful and easy to read. Feel free to comment with your queries and feedback.
You can download a file project from this link.

Like this post? Please share to your friends:
  • Visual basic для word скачать
  • Visual basic для word 2016
  • Visual basic для excel цикл
  • Visual basic для excel учебник скачать
  • Visual basic для excel таблица