How to Load Existing Spreadsheets in C#

In this comprehensive tutorial, we explore how to load existing Excel spreadsheets and CSV files into a C# application using the IronXL library. To begin, ensure the IronXL NuGet package is installed in your project. This can be done easily via the NuGet package manager.

Start by importing the IronXL namespace into your program's C# file and setting your IronXL license key. IronXL supports a variety of Excel formats, including XLSX, XLS, XLSM, and XLTX.

Here's how you can implement this functionality in your C# project:

// Ensure you have installed the IronXL library via NuGet package manager first
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Set your IronXL license key
        IronXL.License.LicenseKey = "YOUR_LICENSE_KEY";

        // Load an Excel file with the specified path and extension (e.g., 'sample.xlsx')
        WorkBook workbook = WorkBook.Load("sample.xlsx");

        // Iterate over the sheets and print the values for demonstration
        foreach (var sheet in workbook.WorkSheets)
        {
            System.Console.WriteLine($"Sheet Name: {sheet.Name}");

            // Read data from the first sheet
            for (int row = 0; row < sheet.RowCount; row++)
            {
                for (int col = 0; col < sheet.ColumnCount; col++)
                {
                    // Print each cell's value
                    System.Console.Write($"{sheet[row, col].StringValue} \t");
                }
                System.Console.WriteLine();
            }
        }

        // Load a CSV file into a new workbook
        WorkBook csvWorkbook = WorkBook.LoadCSV("sample.csv", fileFormat: ExcelFileFormat.XLSX);

        // Perform data manipulation or analysis as required
        // For example, print out data from the CSV
        var csvSheet = csvWorkbook.DefaultWorkSheet;
        System.Console.WriteLine("Data from CSV:");
        for (int row = 0; row < csvSheet.RowCount; row++)
        {
            for (int col = 0; col < csvSheet.ColumnCount; col++)
            {
                // Print each cell's value
                System.Console.Write($"{csvSheet[row, col].StringValue} \t");
            }
            System.Console.WriteLine();
        }

        // Create a new workbook from a dataset (example logic, implementation may vary)
        var dataSetWorkbook = WorkBook.Create();

        // Assume dataset available to load worksheets, load them as required
        // dataSetWorkbook.LoadWorkSheetsFromDataSet(yourDataSet);

        System.Console.WriteLine("Integration complete, data loaded successfully.");
    }
}
// Ensure you have installed the IronXL library via NuGet package manager first
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Set your IronXL license key
        IronXL.License.LicenseKey = "YOUR_LICENSE_KEY";

        // Load an Excel file with the specified path and extension (e.g., 'sample.xlsx')
        WorkBook workbook = WorkBook.Load("sample.xlsx");

        // Iterate over the sheets and print the values for demonstration
        foreach (var sheet in workbook.WorkSheets)
        {
            System.Console.WriteLine($"Sheet Name: {sheet.Name}");

            // Read data from the first sheet
            for (int row = 0; row < sheet.RowCount; row++)
            {
                for (int col = 0; col < sheet.ColumnCount; col++)
                {
                    // Print each cell's value
                    System.Console.Write($"{sheet[row, col].StringValue} \t");
                }
                System.Console.WriteLine();
            }
        }

        // Load a CSV file into a new workbook
        WorkBook csvWorkbook = WorkBook.LoadCSV("sample.csv", fileFormat: ExcelFileFormat.XLSX);

        // Perform data manipulation or analysis as required
        // For example, print out data from the CSV
        var csvSheet = csvWorkbook.DefaultWorkSheet;
        System.Console.WriteLine("Data from CSV:");
        for (int row = 0; row < csvSheet.RowCount; row++)
        {
            for (int col = 0; col < csvSheet.ColumnCount; col++)
            {
                // Print each cell's value
                System.Console.Write($"{csvSheet[row, col].StringValue} \t");
            }
            System.Console.WriteLine();
        }

        // Create a new workbook from a dataset (example logic, implementation may vary)
        var dataSetWorkbook = WorkBook.Create();

        // Assume dataset available to load worksheets, load them as required
        // dataSetWorkbook.LoadWorkSheetsFromDataSet(yourDataSet);

        System.Console.WriteLine("Integration complete, data loaded successfully.");
    }
}
' Ensure you have installed the IronXL library via NuGet package manager first
Imports Microsoft.VisualBasic
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Set your IronXL license key
		IronXL.License.LicenseKey = "YOUR_LICENSE_KEY"

		' Load an Excel file with the specified path and extension (e.g., 'sample.xlsx')
		Dim workbook As WorkBook = WorkBook.Load("sample.xlsx")

		' Iterate over the sheets and print the values for demonstration
		For Each sheet In workbook.WorkSheets
			System.Console.WriteLine($"Sheet Name: {sheet.Name}")

			' Read data from the first sheet
			For row As Integer = 0 To sheet.RowCount - 1
				For col As Integer = 0 To sheet.ColumnCount - 1
					' Print each cell's value
					System.Console.Write($"{sheet(row, col).StringValue} " & vbTab)
				Next col
				System.Console.WriteLine()
			Next row
		Next sheet

		' Load a CSV file into a new workbook
		Dim csvWorkbook As WorkBook = WorkBook.LoadCSV("sample.csv", fileFormat:= ExcelFileFormat.XLSX)

		' Perform data manipulation or analysis as required
		' For example, print out data from the CSV
		Dim csvSheet = csvWorkbook.DefaultWorkSheet
		System.Console.WriteLine("Data from CSV:")
		For row As Integer = 0 To csvSheet.RowCount - 1
			For col As Integer = 0 To csvSheet.ColumnCount - 1
				' Print each cell's value
				System.Console.Write($"{csvSheet(row, col).StringValue} " & vbTab)
			Next col
			System.Console.WriteLine()
		Next row

		' Create a new workbook from a dataset (example logic, implementation may vary)
		Dim dataSetWorkbook = WorkBook.Create()

		' Assume dataset available to load worksheets, load them as required
		' dataSetWorkbook.LoadWorkSheetsFromDataSet(yourDataSet);

		System.Console.WriteLine("Integration complete, data loaded successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel
  • Excel File Loading: The code initializes a WorkBook instance from an existing Excel file using WorkBook.Load().
  • CSV File Loading: CSV files are loaded into a new workbook using WorkBook.LoadCSV().
  • Data Manipulation: It demonstrates accessing data from cells and outputting to console, which can be extended for more complex data manipulation and analysis.
  • Creating New WorkBook: The snippet shows how you might start creating a WorkBook from a dataset, although loading directly from a dataset depends on the specific structure of the dataset in use.

By following these outlined steps, you can effectively manage existing spreadsheets and CSV files in your C# projects, leveraging the capabilities of IronXL.

We hope this tutorial is beneficial. Subscribe for more informative tutorials from Myer Software, and sign up for IronXL's trial to experience its capabilities firsthand.

Further Reading: How to Load Existing Spreadsheets

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
How to Use Math Functions in Excel
NEXT >
How to Create Hyperlinks in Excel Using C#