IronSoftware
  • Products
    for .NET Java
    Create, read, and edit PDFs
    for .NET
    Image to text in 127 languages
    for .NET
    Read and write QR & Barcodes
    for .NET
    No Office Interop required
    for .NET
    Extract structured data from websites
    5 for the Price of 2 All 5 .NET product licenses from $1498 Save 60% with Iron Suite Iron Suites - Donate $50
  • Open Source
    for .NET
    System.Drawing.Common Replacement
  • About Us
  • Contact Us

205 N. Michigan Ave. Chicago, IL 60611, USA +1 (312) 500-3060

Join Iron Slack

  • Home
  • Licensing
  • EULA
  • Support & Update Extensions
  • License Upgrades
  • Get Started
  • Features
  • Code Examples
  • Tutorials
  • How-Tos
  • Troubleshooting
  • Product Updates
  • API Reference
  • Search
  • Free NuGet Download
IronXL - Excel Library for C# .NET IronXL - Excel Library for C# .NET
  • Home
  • Licensing
    • Licensing
    • EULA
    • Support & Update Extensions
    • License Upgrades
  • Docs
    • Search
    • Get Started
    • Features
    • Code Examples
    • Tutorials
    • How-Tos
    • Troubleshooting
    • Product Updates
    • API Reference
    • Search
  • Search
  • Free NuGet Download Total downloads: 308,082
Message's icon

The C# Excel Library

  • # Intuitive C# & VB.NET Excel API
  • # No need to install MS Office or Excel Interop
  • # Read, edit & create Excel spreadsheet files
  • # Fully supports .NET Core, Framework, and Azure
Explore IronXL Free NuGet Download

Examples

  • Read Excel Files without Interop
  • Excel Worksheets
  • Create Excel Files
  • Convert Spreadsheet File Types
  • Excel to SQL via System.Data.DataSet
  • Excel to SQL and DataGrid via DataTable
  • Excel Conditional Formatting
  • Protect Excel Files
  • Excel Formulas in C#
  • Edit Excel Metadata in C#
  • Update Excel Database Records
  • Style Excel Cell Borders & Fonts
  • Sort Excel Ranges in C#
  • Repeat Excel Rows & Columns
  • Excel Print Setup
  • Cell Data Display Format
  • Load Excel From SQL Database
  • Combine Excel Ranges
  • Select Excel Range
  • Convert Excel to HTML
  • Aggregate Excel Functions
  • Create Excel Line Chart
  • Freeze Panes in Excel
  • Copy Excel Worksheets
Read Excel Files without Interop
using IronXL;
using System;
using System.Linq;

// Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Select worksheet at index 0
WorkSheet workSheet = workBook.WorkSheets[0];

// Get any existing worksheet
WorkSheet firstSheet = workBook.DefaultWorkSheet;

// Select a cell and return the converted value
int cellValue = workSheet["A2"].IntValue;

// Read from ranges of cells elegantly.
foreach (var cell in workSheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Calculate aggregate values such as Min, Max and Sum
decimal sum = workSheet["A2:A10"].Sum();

// Linq compatible
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
Imports IronXL
Imports System
Imports System.Linq

' Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Select worksheet at index 0
Private workSheet As WorkSheet = workBook.WorkSheets(0)

' Get any existing worksheet
Private firstSheet As WorkSheet = workBook.DefaultWorkSheet

' Select a cell and return the converted value
Private cellValue As Integer = workSheet("A2").IntValue

' Read from ranges of cells elegantly.
For Each cell In workSheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

' Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = workSheet("A2:A10").Sum()

' Linq compatible
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue)
Excel Worksheets
using IronXL;

// Create new Excel spreadsheet
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Create worksheets (workSheet1, workSheet2, workSheet3)
WorkSheet workSheet1 = workBook.CreateWorkSheet("workSheet1");
WorkSheet workSheet2 = workBook.CreateWorkSheet("workSheet2");
WorkSheet workSheet3 = workBook.CreateWorkSheet("workSheet3");

// Set worksheet position (workSheet2, workSheet1, workSheet3)
workBook.SetSheetPosition("workSheet2", 0);

// Set active for workSheet3
workBook.SetActiveTab(2);

// Remove workSheet1
workBook.RemoveWorkSheet(1);

workBook.SaveAs("controllingWorkSheet.xlsx");
Imports IronXL

' Create new Excel spreadsheet
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Create worksheets (workSheet1, workSheet2, workSheet3)
Private workSheet1 As WorkSheet = workBook.CreateWorkSheet("workSheet1")
Private workSheet2 As WorkSheet = workBook.CreateWorkSheet("workSheet2")
Private workSheet3 As WorkSheet = workBook.CreateWorkSheet("workSheet3")

' Set worksheet position (workSheet2, workSheet1, workSheet3)
workBook.SetSheetPosition("workSheet2", 0)

' Set active for workSheet3
workBook.SetActiveTab(2)

' Remove workSheet1
workBook.RemoveWorkSheet(1)

workBook.SaveAs("controllingWorkSheet.xlsx")
Create Excel Files
using IronXL;

// Create new Excel WorkBook document
WorkBook workBook = WorkBook.Create();

// Convert XLSX to XLS
WorkBook xlsWorkBook = WorkBook.Create(ExcelFileFormat.XLS);

// Create a blank WorkSheet
WorkSheet workSheet = workBook.CreateWorkSheet("new_sheet");

// Add data and styles to the new worksheet
workSheet["A1"].Value = "Hello World";
workSheet["A1"].Style.WrapText = true;
workSheet["A2"].BoolValue = true;
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;

// Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
workBook.SaveAs("sample.xlsx");
Imports IronXL

' Create new Excel WorkBook document
Private workBook As WorkBook = WorkBook.Create()

' Convert XLSX to XLS
Private xlsWorkBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)

' Create a blank WorkSheet
Private workSheet As WorkSheet = workBook.CreateWorkSheet("new_sheet")

' Add data and styles to the new worksheet
Private workSheet("A1").Value = "Hello World"
Private workSheet("A1").Style.WrapText = True
Private workSheet("A2").BoolValue = True
Private workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double

' Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
workBook.SaveAs("sample.xlsx")
Convert Spreadsheet File Types
using IronXL;
using System.IO;


// Import any XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Export the excel file as XLS, XLSX, XLSM, CSV, TSV, JSON, XML
workBook.SaveAs("sample.xls");
workBook.SaveAs("sample.xlsx");
workBook.SaveAs("sample.tsv");
workBook.SaveAsCsv("sample.csv");
workBook.SaveAsJson("sample.json");
workBook.SaveAsXml("sample.xml");

// Export the excel file as Html, Html string
workBook.ExportToHtml("sample.html");
string htmlString = workBook.ExportToHtmlString();

// Export the excel file as Binary, Byte array, Data set, Stream
byte[] binary = workBook.ToBinary();
byte[] byteArray = workBook.ToByteArray();
System.Data.DataSet dataSet = workBook.ToDataSet(); // Allow easy integration with DataGrids, SQL and EF
Stream stream = workBook.ToStream();
Imports IronXL
Imports System.IO


' Import any XLSX, XLS, XLSM, XLTX, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Export the excel file as XLS, XLSX, XLSM, CSV, TSV, JSON, XML
workBook.SaveAs("sample.xls")
workBook.SaveAs("sample.xlsx")
workBook.SaveAs("sample.tsv")
workBook.SaveAsCsv("sample.csv")
workBook.SaveAsJson("sample.json")
workBook.SaveAsXml("sample.xml")

' Export the excel file as Html, Html string
workBook.ExportToHtml("sample.html")
Dim htmlString As String = workBook.ExportToHtmlString()

' Export the excel file as Binary, Byte array, Data set, Stream
Dim binary() As Byte = workBook.ToBinary()
Dim byteArray() As Byte = workBook.ToByteArray()
Dim dataSet As System.Data.DataSet = workBook.ToDataSet() ' Allow easy integration with DataGrids, SQL and EF
Dim stream As Stream = workBook.ToStream()
Excel to SQL via System.Data.DataSet
using IronXL;
using System;
using System.Data;

// Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Convert the whole Excel WorkBook to a DataSet
DataSet dataSet = workBook.ToDataSet();

foreach (DataTable table in dataSet.Tables)
{
    Console.WriteLine(table.TableName);

    // Enumerate by rows or columns first at your preference
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i]);
        }
    }
}
Imports IronXL
Imports System
Imports System.Data

' Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Convert the whole Excel WorkBook to a DataSet
Private dataSet As DataSet = workBook.ToDataSet()

For Each table As DataTable In dataSet.Tables
	Console.WriteLine(table.TableName)

	' Enumerate by rows or columns first at your preference
	For Each row As DataRow In table.Rows
		For i As Integer = 0 To table.Columns.Count - 1
			Console.Write(row(i))
		Next i
	Next row
Next table
Excel to SQL and DataGrid via DataTable
using IronXL;
using System;
using System.Data;

// Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Select default sheet
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Convert the worksheet to DataTable
DataTable dataTable = workSheet.ToDataTable(true);

// Enumerate by rows or columns first at your preference
foreach (DataRow row in dataTable.Rows)
{
    for (int i = 0; i < dataTable.Columns.Count; i++)
    {
        Console.Write(row[i]);
    }
}
Imports IronXL
Imports System
Imports System.Data

' Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Select default sheet
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Convert the worksheet to DataTable
Private dataTable As DataTable = workSheet.ToDataTable(True)

' Enumerate by rows or columns first at your preference
For Each row As DataRow In dataTable.Rows
	For i As Integer = 0 To dataTable.Columns.Count - 1
		Console.Write(row(i))
	Next i
Next row
Excel Conditional Formatting
using IronXL;
using IronXL.Styles;
using IronXL.Formatting.Enums;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Create conditional formatting rule
var rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.LessThan, "8");
// Set style options
rule.FontFormatting.IsBold = true;
rule.FontFormatting.FontColor = "#123456";
rule.BorderFormatting.RightBorderColor = "#ffffff";
rule.BorderFormatting.RightBorderType = BorderType.Thick;
rule.PatternFormatting.BackgroundColor = "#54bdd9";
rule.PatternFormatting.FillPattern = FillPattern.Diamonds;
// Apply formatting on specified region
workSheet.ConditionalFormatting.AddConditionalFormatting("A3:A8", rule);

// Create conditional formatting rule
var rule1 = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.Between, "7", "10");
// Set style options
rule1.FontFormatting.IsItalic = true;
rule1.FontFormatting.UnderlineType = FontUnderlineType.Single;
// Apply formatting on specified region
workSheet.ConditionalFormatting.AddConditionalFormatting("A3:A9", rule1);

workBook.SaveAs("applyConditionalFormatting.xlsx");
Imports IronXL
Imports IronXL.Styles
Imports IronXL.Formatting.Enums

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Create conditional formatting rule
Private rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.LessThan, "8")
' Set style options
rule.FontFormatting.IsBold = True
rule.FontFormatting.FontColor = "#123456"
rule.BorderFormatting.RightBorderColor = "#ffffff"
rule.BorderFormatting.RightBorderType = BorderType.Thick
rule.PatternFormatting.BackgroundColor = "#54bdd9"
rule.PatternFormatting.FillPattern = FillPattern.Diamonds
' Apply formatting on specified region
workSheet.ConditionalFormatting.AddConditionalFormatting("A3:A8", rule)

' Create conditional formatting rule
Dim rule1 = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.Between, "7", "10")
' Set style options
rule1.FontFormatting.IsItalic = True
rule1.FontFormatting.UnderlineType = FontUnderlineType.Single
' Apply formatting on specified region
workSheet.ConditionalFormatting.AddConditionalFormatting("A3:A9", rule1)

workBook.SaveAs("applyConditionalFormatting.xlsx")
Protect Excel Files
using IronXL;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Open protected spreadsheet file
WorkBook protectedWorkBook = WorkBook.Load("sample.xlsx", "IronSoftware");

// Spreadsheet protection
// Set protection for spreadsheet file
workBook.Encrypt("IronSoftware");

// Remove protection for spreadsheet file. Original password is required.
workBook.Password = null;

// Worksheet protection
// Set protection for individual worksheet
workSheet.ProtectSheet("IronXL");

// Remove protection for particular worksheet. It works without password!
workSheet.UnprotectSheet();

workBook.Save();
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Open protected spreadsheet file
Private protectedWorkBook As WorkBook = WorkBook.Load("sample.xlsx", "IronSoftware")

' Spreadsheet protection
' Set protection for spreadsheet file
workBook.Encrypt("IronSoftware")

' Remove protection for spreadsheet file. Original password is required.
workBook.Password = Nothing

' Worksheet protection
' Set protection for individual worksheet
workSheet.ProtectSheet("IronXL")

' Remove protection for particular worksheet. It works without password!
workSheet.UnprotectSheet()

workBook.Save()
Excel Formulas in C#
using IronXL;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set Formulas
workSheet["A1"].Formula = "Sum(B8:C12)";
workSheet["B8"].Formula = "=C9/C11";
workSheet["G30"].Formula = "Max(C3:C7)";

// Force recalculate all formula values in all sheets.
workBook.EvaluateAll();

// Get the formula's calculated value.  e.g. "52"
var formulaValue = workSheet["G30"].First().FormattedCellValue;

// Get the formula as a string. e.g. "Max(C3:C7)"
string formulaString = workSheet["G30"].Formula;

// Save changes with updated formulas and calculated values.
workBook.Save();
Imports IronXL
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set Formulas
Private workSheet("A1").Formula = "Sum(B8:C12)"
Private workSheet("B8").Formula = "=C9/C11"
Private workSheet("G30").Formula = "Max(C3:C7)"

' Force recalculate all formula values in all sheets.
workBook.EvaluateAll()

' Get the formula's calculated value.  e.g. "52"
Dim formulaValue = workSheet("G30").First().FormattedCellValue

' Get the formula as a string. e.g. "Max(C3:C7)"
Dim formulaString As String = workSheet("G30").Formula

' Save changes with updated formulas and calculated values.
workBook.Save()
Edit Excel Metadata in C#
using IronXL;
using System;

WorkBook workBook = WorkBook.Load("sample.xlsx");

// Set author
workBook.Metadata.Author = "Your Name";
// Set comments
workBook.Metadata.Comments = "Monthly report";
// Set title
workBook.Metadata.Title = "July";
// Set keywords
workBook.Metadata.Keywords = "Report";

// Read the creation date of the excel file
DateTime? creationDate = workBook.Metadata.Created;

// Read the last printed date of the excel file
DateTime? printDate = workBook.Metadata.LastPrinted;

workBook.SaveAs("editedMetadata.xlsx");
Imports IronXL
Imports System

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Set author
workBook.Metadata.Author = "Your Name"
' Set comments
workBook.Metadata.Comments = "Monthly report"
' Set title
workBook.Metadata.Title = "July"
' Set keywords
workBook.Metadata.Keywords = "Report"

' Read the creation date of the excel file
Dim creationDate? As DateTime = workBook.Metadata.Created

' Read the last printed date of the excel file
Dim printDate? As DateTime = workBook.Metadata.LastPrinted

workBook.SaveAs("editedMetadata.xlsx")
Update Excel Database Records
using IronXL;
using System.Data;
using System.Data.SqlClient;

// Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Convert the workbook to ToDataSet
DataSet dataSet = workBook.ToDataSet();

// Your sql query
string sql = "SELECT * FROM Users";

// Your connection string
string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Open connections to the database
    connection.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);

    // Update the values in database using the values in Excel
    adapter.Update(dataSet);
}
Imports IronXL
Imports System.Data
Imports System.Data.SqlClient

' Supported for XLSX, XLS, XLSM, XLTX, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

' Convert the workbook to ToDataSet
Private dataSet As DataSet = workBook.ToDataSet()

' Your sql query
Private sql As String = "SELECT * FROM Users"

' Your connection string
Private connectionString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True"
Using connection As New SqlConnection(connectionString)
	' Open connections to the database
	connection.Open()
	Dim adapter As New SqlDataAdapter(sql, connection)

	' Update the values in database using the values in Excel
	adapter.Update(dataSet)
End Using
Style Excel Cell Borders & Fonts
using IronXL;
using IronXL.Styles;
using IronSoftware.Drawing;
using System.Linq;


WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

var range = workSheet["A1:H10"];

var cell = range.First();

// Set background color of the cell with an rgb string
cell.Style.SetBackgroundColor("#428D65");

// Apply styling to the whole range.

// Set underline property to the font
// FontUnderlineType is enum that stands for different types of font underlying
range.Style.Font.Underline = FontUnderlineType.SingleAccounting;

// Define whether to use horizontal line through the text or not
range.Style.Font.Strikeout = false;

// Define whether the font is bold or not
range.Style.Font.Bold = true;

// Define whether the font is italic or not
range.Style.Font.Italic = false;

// Get or set script property of a font
// Font script enum stands for available options
range.Style.Font.FontScript = FontScript.Super;

// Set the type of the border line
// There are also TopBorder,LeftBorder,RightBorder,DiagonalBorder properties
// BorderType enum indicates the line style of a border in a cell
range.Style.BottomBorder.Type = BorderType.MediumDashed;

// Indicate whether the cell should be auto-sized
range.Style.ShrinkToFit = true;

// Set alignment of the cell
range.Style.VerticalAlignment = VerticalAlignment.Bottom;

// Set border color
range.Style.DiagonalBorder.SetColor("#20C96F");

// Define border type and border direction as well
range.Style.DiagonalBorder.Type = BorderType.Thick;

// DiagonalBorderDirection enum stands for direction of diagonal border inside cell
range.Style.DiagonalBorderDirection = DiagonalBorderDirection.Forward;

// Set background color of cells
range.Style.SetBackgroundColor(Color.Aquamarine);

// Set fill pattern of the cell
// FillPattern enum indicates the style of fill pattern
range.Style.FillPattern = FillPattern.Diamonds;

// Set the number of spaces to intend the text
range.Style.Indention = 5;

// Indicate if the text is wrapped
range.Style.WrapText = true;

workBook.SaveAs("stylingOptions.xls");
Imports IronXL
Imports IronXL.Styles
Imports IronSoftware.Drawing
Imports System.Linq


Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

Private range = workSheet("A1:H10")

Private cell = range.First()

' Set background color of the cell with an rgb string
cell.Style.SetBackgroundColor("#428D65")

' Apply styling to the whole range.

' Set underline property to the font
' FontUnderlineType is enum that stands for different types of font underlying
range.Style.Font.Underline = FontUnderlineType.SingleAccounting

' Define whether to use horizontal line through the text or not
range.Style.Font.Strikeout = False

' Define whether the font is bold or not
range.Style.Font.Bold = True

' Define whether the font is italic or not
range.Style.Font.Italic = False

' Get or set script property of a font
' Font script enum stands for available options
range.Style.Font.FontScript = FontScript.Super

' Set the type of the border line
' There are also TopBorder,LeftBorder,RightBorder,DiagonalBorder properties
' BorderType enum indicates the line style of a border in a cell
range.Style.BottomBorder.Type = BorderType.MediumDashed

' Indicate whether the cell should be auto-sized
range.Style.ShrinkToFit = True

' Set alignment of the cell
range.Style.VerticalAlignment = VerticalAlignment.Bottom

' Set border color
range.Style.DiagonalBorder.SetColor("#20C96F")

' Define border type and border direction as well
range.Style.DiagonalBorder.Type = BorderType.Thick

' DiagonalBorderDirection enum stands for direction of diagonal border inside cell
range.Style.DiagonalBorderDirection = DiagonalBorderDirection.Forward

' Set background color of cells
range.Style.SetBackgroundColor(Color.Aquamarine)

' Set fill pattern of the cell
' FillPattern enum indicates the style of fill pattern
range.Style.FillPattern = FillPattern.Diamonds

' Set the number of spaces to intend the text
range.Style.Indention = 5

' Indicate if the text is wrapped
range.Style.WrapText = True

workBook.SaveAs("stylingOptions.xls")
Sort Excel Ranges in C#
using IronXL;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Select a range
var range = workSheet["A1:D20"];

// Select a column(B)
var column = workSheet.GetColumn(1);

// Sort the range in ascending order (A to Z)
range.SortAscending();

// Sort the range by column(C) in ascending order
range.SortByColumn("C", SortOrder.Ascending);

// Sort the column(B) in descending order (Z to A)
column.SortDescending();

workBook.SaveAs("sortExcelRange.xlsx");
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Select a range
Private range = workSheet("A1:D20")

' Select a column(B)
Private column = workSheet.GetColumn(1)

' Sort the range in ascending order (A to Z)
range.SortAscending()

' Sort the range by column(C) in ascending order
range.SortByColumn("C", SortOrder.Ascending)

' Sort the column(B) in descending order (Z to A)
column.SortDescending()

workBook.SaveAs("sortExcelRange.xlsx")
Repeat Excel Rows & Columns
using IronXL;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set repeating rows for row(2-4)
workSheet.SetRepeatingRows(1, 3);

// Set repeating columns for column(C-D)
workSheet.SetRepeatingColumns(2, 3);

// Set column break after column(H). Hence, the first page will only contain column(A-G)
workSheet.SetColumnBreak(7);

workBook.SaveAs("repeatingRows.xlsx");
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set repeating rows for row(2-4)
workSheet.SetRepeatingRows(1, 3)

' Set repeating columns for column(C-D)
workSheet.SetRepeatingColumns(2, 3)

' Set column break after column(H). Hence, the first page will only contain column(A-G)
workSheet.SetColumnBreak(7)

workBook.SaveAs("repeatingRows.xlsx")
Excel Print Setup
using IronXL;
using IronXL.Printing;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the print header and footer of the worksheet
workSheet.Header.Center = "My document";
workSheet.Footer.Center = "Page &P of &N";

// Set the header margin
workSheet.PrintSetup.HeaderMargin = 2.33;

// Set the size of the paper
// Paper size enum represents different sizes of paper
workSheet.PrintSetup.PaperSize = PaperSize.B4;

// Set the print orientation of the worksheet
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Portrait;

// Set black and white printing
workSheet.PrintSetup.NoColor = true;

workBook.SaveAs("PrintSetup.xlsx");
Imports IronXL
Imports IronXL.Printing

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set the print header and footer of the worksheet
workSheet.Header.Center = "My document"
workSheet.Footer.Center = "Page &P of &N"

' Set the header margin
workSheet.PrintSetup.HeaderMargin = 2.33

' Set the size of the paper
' Paper size enum represents different sizes of paper
workSheet.PrintSetup.PaperSize = PaperSize.B4

' Set the print orientation of the worksheet
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Portrait

' Set black and white printing
workSheet.PrintSetup.NoColor = True

workBook.SaveAs("PrintSetup.xlsx")
Cell Data Display Format
using IronXL;
using System;
using System.Linq;

// Load an existing WorkSheet
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Set data display format to cell
// The cell value will look like 12300%
workSheet["A2"].Value = 123;
workSheet["A2"].FormatString = "0.0%";

// The cell value will look like 123.0000
workSheet["A2"].First().FormatString = "0.0000";

// Set data display format to range
DateTime dateValue = new DateTime(2020, 1, 1, 12, 12, 12);
workSheet["A3"].Value = dateValue;
workSheet["A4"].First().Value = new DateTime(2022, 3, 3, 10, 10, 10);
workSheet["A5"].First().Value = new DateTime(2021, 2, 2, 11, 11, 11);

var range = workSheet["A3:A5"];

// The cell(A3) value will look like 1/1/2020 12:12:12 PM
range.FormatString = "MM/dd/yy h:mm:ss";

workBook.SaveAs("numberFormats.xls");
Imports IronXL
Imports System
Imports System.Linq

' Load an existing WorkSheet
Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Set data display format to cell
' The cell value will look like 12300%
Private workSheet("A2").Value = 123
Private workSheet("A2").FormatString = "0.0%"

' The cell value will look like 123.0000
workSheet("A2").First().FormatString = "0.0000"

' Set data display format to range
Dim dateValue As New DateTime(2020, 1, 1, 12, 12, 12)
workSheet("A3").Value = dateValue
workSheet("A4").First().Value = New DateTime(2022, 3, 3, 10, 10, 10)
workSheet("A5").First().Value = New DateTime(2021, 2, 2, 11, 11, 11)

Dim range = workSheet("A3:A5")

' The cell(A3) value will look like 1/1/2020 12:12:12 PM
range.FormatString = "MM/dd/yy h:mm:ss"

workBook.SaveAs("numberFormats.xls")
Load Excel From SQL Database
using IronXL;
using System.Data;
using System.Data.SqlClient;

// Your sql query
string sql = "SELECT * FROM Users";

// Your connection string
string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Open connections to the database
    connection.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
    DataSet ds = new DataSet();
    // Fill DataSet with data
    adapter.Fill(ds);

    // Create an Excel workbook from the SQL DataSet
    WorkBook workBook = WorkBook.Load(ds);
}
Imports IronXL
Imports System.Data
Imports System.Data.SqlClient

' Your sql query
Private sql As String = "SELECT * FROM Users"

' Your connection string
Private connectionString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=usersdb;Integrated Security=True"

Using connection As New SqlConnection(connectionString)
	' Open connections to the database
	connection.Open()
	Dim adapter As New SqlDataAdapter(sql, connection)
	Dim ds As New DataSet()
	' Fill DataSet with data
	adapter.Fill(ds)

	' Create an Excel workbook from the SQL DataSet
	Dim workBook As WorkBook = WorkBook.Load(ds)
End Using
Combine Excel Ranges
using IronXL;
using System;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Get a range from an Excel worksheet
var range = workSheet["A2:A8"];

// Combine two ranges
var combinedRange = range + workSheet["A9:A10"];

// Iterate over combined range
foreach (var cell in combinedRange)
{
    Console.WriteLine(cell.Value);
}
Imports IronXL
Imports System
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Get a range from an Excel worksheet
Private range = workSheet("A2:A8")

' Combine two ranges
Private combinedRange = range + workSheet("A9:A10")

' Iterate over combined range
For Each cell In combinedRange
	Console.WriteLine(cell.Value)
Next cell
Select Excel Range
using IronXL;
using System;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Get range from worksheet
var range = workSheet["A2:A8"];

// Get column from worksheet
var columnA = workSheet.GetColumn(0);

// Get row from worksheet
var row1 = workSheet.GetRow(0);

// Iterate over the range
foreach (var cell in range)
{
    Console.WriteLine($"{cell.Value}");
}

// Select and print every row
var rows = workSheet.Rows;

foreach (var eachRow in rows)
{
    foreach (var cell in eachRow)
    {
        Console.Write($"  {cell.Value}  |");
    }
    Console.WriteLine($"");
}
Imports IronXL
Imports System
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Get range from worksheet
Private range = workSheet("A2:A8")

' Get column from worksheet
Private columnA = workSheet.GetColumn(0)

' Get row from worksheet
Private row1 = workSheet.GetRow(0)

' Iterate over the range
For Each cell In range
	Console.WriteLine($"{cell.Value}")
Next cell

' Select and print every row
Dim rows = workSheet.Rows

For Each eachRow In rows
	For Each cell In eachRow
		Console.Write($"  {cell.Value}  |")
	Next cell
	Console.WriteLine($"")
Next eachRow
Convert Excel to HTML
using IronXL;
using IronXL.Options;

WorkBook workBook = WorkBook.Load("sample.xlsx");

var options = new HtmlExportOptions()
{
    // Set row/column numbers visible in html document
    OutputRowNumbers = true,
    OutputColumnHeaders = true,

    // Set hidden rows/columns visible in html document
    OutputHiddenRows = true,
    OutputHiddenColumns = true,

    // Set leading spaces as non-breaking
    OutputLeadingSpacesAsNonBreaking = true
};

// Export workbook to the HTML file
workBook.ExportToHtml("workBook.html", options);
Imports IronXL
Imports IronXL.Options

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")

Private options = New HtmlExportOptions() With {
	.OutputRowNumbers = True,
	.OutputColumnHeaders = True,
	.OutputHiddenRows = True,
	.OutputHiddenColumns = True,
	.OutputLeadingSpacesAsNonBreaking = True
}

' Export workbook to the HTML file
workBook.ExportToHtml("workBook.html", options)
Aggregate Excel Functions
using IronXL;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Get range from worksheet
var range = workSheet["A1:A8"];

// Apply sum of all numeric cells within the range
decimal sum = range.Sum();

// Apply average value of all numeric cells within the range
decimal avg = range.Avg();

// Identify maximum value of all numeric cells within the range
decimal max = range.Max();

// Identify minimum value of all numeric cells within the range
decimal min = range.Min();
Imports IronXL
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Get range from worksheet
Private range = workSheet("A1:A8")

' Apply sum of all numeric cells within the range
Private sum As Decimal = range.Sum()

' Apply average value of all numeric cells within the range
Private avg As Decimal = range.Avg()

' Identify maximum value of all numeric cells within the range
Private max As Decimal = range.Max()

' Identify minimum value of all numeric cells within the range
Private min As Decimal = range.Min()
Create Excel Line Chart
using IronXL;
using IronXL.Drawing.Charts;

WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the chart type and it's position  on the worksheet.
var chart = workSheet.CreateChart(ChartType.Line, 10, 10, 18, 20);

// Add the series to the chart
// The first parameter represents the address of the range for horizontal(category) axis.
// The second  parameter represents the address of the range for vertical(value) axis.
var series = chart.AddSeries("B3:B8", "A3:A8");

// Set the chart title.
series.Title = "Line Chart";

// Set the legend position.
// Can be removed by setting it to None.
chart.SetLegendPosition(LegendPosition.Bottom);

// We can change the position of the chart.
chart.Position.LeftColumnIndex = 2;
chart.Position.RightColumnIndex = chart.Position.LeftColumnIndex + 3;

// Plot all the data that was added to the chart before.
// Multiple call of this method leads to plotting multiple charts instead of modifying the existing chart.
// Yet there is no possibility to remove chart or edit it's series/position.
// We can just create new one.
chart.Plot();

workBook.SaveAs("CreateLineChart.xlsx");
Imports IronXL
Imports IronXL.Drawing.Charts

Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set the chart type and it's position  on the worksheet.
Private chart = workSheet.CreateChart(ChartType.Line, 10, 10, 18, 20)

' Add the series to the chart
' The first parameter represents the address of the range for horizontal(category) axis.
' The second  parameter represents the address of the range for vertical(value) axis.
Private series = chart.AddSeries("B3:B8", "A3:A8")

' Set the chart title.
series.Title = "Line Chart"

' Set the legend position.
' Can be removed by setting it to None.
chart.SetLegendPosition(LegendPosition.Bottom)

' We can change the position of the chart.
chart.Position.LeftColumnIndex = 2
chart.Position.RightColumnIndex = chart.Position.LeftColumnIndex + 3

' Plot all the data that was added to the chart before.
' Multiple call of this method leads to plotting multiple charts instead of modifying the existing chart.
' Yet there is no possibility to remove chart or edit it's series/position.
' We can just create new one.
chart.Plot()

workBook.SaveAs("CreateLineChart.xlsx")
Freeze Panes in Excel
using IronXL;
using System.Linq;

WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();

// Create freeze pane from column(A-B) and row(1-3)
workSheet.CreateFreezePane(2, 3);

// Overwriting freeze or split pane to column(A-E) and row(1-5) as well as applying prescroll
// The column will show E,G,... and the row will show 5,8,...
workSheet.CreateFreezePane(5, 5, 6, 7);

workBook.SaveAs("createFreezePanes.xls");

// Remove all existing freeze or split pane
workSheet.RemovePane();
Imports IronXL
Imports System.Linq

Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Create freeze pane from column(A-B) and row(1-3)
workSheet.CreateFreezePane(2, 3)

' Overwriting freeze or split pane to column(A-E) and row(1-5) as well as applying prescroll
' The column will show E,G,... and the row will show 5,8,...
workSheet.CreateFreezePane(5, 5, 6, 7)

workBook.SaveAs("createFreezePanes.xls")

' Remove all existing freeze or split pane
workSheet.RemovePane()
Copy Excel Worksheets
using IronXL;

WorkBook firstBook = WorkBook.Load("sample.xlsx");
WorkBook secondBook = WorkBook.Create();

// Select first worksheet in the workbook
WorkSheet workSheet = firstBook.DefaultWorkSheet;

// Duplicate the worksheet to the same workbook
workSheet.CopySheet("Copied Sheet");

// Duplicate the worksheet to another workbook with the specified name
workSheet.CopyTo(secondBook, "Copied Sheet");

firstBook.Save();
secondBook.SaveAs("copyExcelWorksheet.xlsx");
Imports IronXL

Private firstBook As WorkBook = WorkBook.Load("sample.xlsx")
Private secondBook As WorkBook = WorkBook.Create()

' Select first worksheet in the workbook
Private workSheet As WorkSheet = firstBook.DefaultWorkSheet

' Duplicate the worksheet to the same workbook
workSheet.CopySheet("Copied Sheet")

' Duplicate the worksheet to another workbook with the specified name
workSheet.CopyTo(secondBook, "Copied Sheet")

firstBook.Save()
secondBook.SaveAs("copyExcelWorksheet.xlsx")
IronXL
  1. IronXL
  2. IronXL Blog
  3. Excel Tools

Excel Tools

  • All Articles
  • Using IronXL
  • Compare to Other Components
  • Excel Tools

April 20, 2022

How to Add Up a Column in Excel

This tutorial covers how To sum the total of a whole column, which are some things most people got to do quite often.

Read More >

April 19, 2022

How to Switch Columns in Excel

This tutorial covers how To switch or shift multiple columns. To change adjacent columns is something most people got to do quite often.

Read More >

Ready to get started? Version: 2022.12 just released

Start for Free Total downloads: 308,082
View Licenses >
Try IronXL for Free
Get Set Up in 5 Minutes
C# NuGet Library for PDF
Install with NuGet
Version: 2022.12
Install-Package IronXL.Excel
nuget.org/packages/IronXL.Excel/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronXL"
  3. Select the package and install
C# PDF DLL
Download DLL
Version: 2022.12
Download Now
Manually install into your project
  1. Download and unzip IronXL to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronXL.dll"
Licenses from $749

Have a question? Get in touch with our development team.

Now that you’ve downloaded IronXL
Want to deploy IronXL to a live project for FREE?
Not ready to buy?

Want to deploy IronXL to a live project for FREE?

What’s included?
30 days of fully-functional product
Test and share in a live environment
No restrictions in production
Get your free 30-day Trial Key instantly.
Thank you.
If you'd like to speak to our licensing team:
Schedule a call
Have a question? Get in touch with our development team.
No credit card or account creation required
Your Trial License Key has been emailed to you.
Not ready to buy?
Thank you.
View your license options:
Thank you.
If you'd like to speak to our licensing team:
View Licensing
Schedule a call
Have a question? Get in touch with our development team.
Have a question? Get in touch with our development team.
Want to deploy IronXL to a live project for FREE?
Not ready to buy?

Want to deploy IronXL to a live project for FREE?

What’s included?
30 days of fully-functional product
Test and share in a live environment
No restrictions in production
Get your free 30-day Trial Key instantly.
Thank you.
If you'd like to speak to our licensing team:
Schedule a call
Have a question? Get in touch with our development team.
No credit card or account creation required
Your Trial License Key has been emailed to you.
Not ready to buy?
Download IronXL free to apply
your Trial Licenses Key
Thank you.
If you'd like to speak to our licensing team:
Install with NuGet View Licensing
Schedule a call
Licenses from $749. Have a question? Get in touch.
Have a question? Get in touch with our development team.
Free 30-Day Trial Key

Fully-functional product, get the key instantly

IronXL for .NET

The Excel API you need, without the Office Interop hassle.

Search

Documentation

  • Code Examples
  • API Reference
  • How-Tos
  • Features
  • Blog
  • Credits
  • Product Brochure

Tutorials

  • Get Started
  • Read an Excel File in C#
  • Create Excel Files in .NET

Licensing

  • Buy a License
  • Support Extensions
  • Resellers
  • License Keys
  • EULA

Try IronXL Free

  • Download on NuGet
  • Download DLL

  • 30-Day Trial License

When you need your PDF to look like HTML, fast.

Tesseract 5 OCR in the languages you need, We support 127+.

When you need to read, write, and style, QR & Barcodes, fast.

The Excel API you need, without the Office Interop hassle.

The power you need to scrape & output clean, structured data.

The complete .NET Suite for your office.

  • IRONSUITE
  • |
  • IRONPDF
  • IRONOCR
  • IRONBARCODE
  • IRONXL
  • IRONWEBSCRAPER
IronSoftware
205 N. Michigan Ave. Chicago, IL 60611 USA +1 (312) 500-3060
  • About Us
  • News
  • Careers
  • Contact Us
  • Join Iron Slack

Supporting Teamseas

Copyright © Iron Software LLC 2013-2023

  • Terms
  • Privacy

Thank you!

Your license key has been delivered to the email provided. Contact us

24-Hour Upgrade Offer:

Save 50% on a
Professional Upgrade

Go Professional to cover 10 developers
and unlimited projects.

hours

:

minutes

:

seconds

Upgrade to Professional

Upgrade

Professional

$600 USD

$299 USD


  • 10 developers
  • 10 locations
  • 10 projects
TODAY ONLY
Iron Suite

5 .NET Products for the Price of 2

IronPDF IronOCR IronXL IronBarcode IronWebscraper

Total Suite Value:

$7,192 USD

Upgrade price

TODAY
ONLY

$499 USD

After 24 Hrs

$1,098 USD