C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

Export and Import Excel Data in C#

When working with Excel files in C#, you can use libraries like EPPlus. A well-liked open-source library called EPPlus makes producing, reading, and altering Excel files simple. Using EPPlus, follow these instructions to export and import Excel data.

What is NPOI?

NPOI is an abbreviation for “Non-Profit Open XML Interface” It is a free and open-source library for working with Microsoft Office documents, especially Word papers, Power Point presentations, and Excel spreadsheets. NPOI enables developers to create, read, write, and manipulate Office documents without install Microsoft Office.

  • NPOI was created to interact with the Open XML formats that Microsoft included in their Office 2007 suite. Based on XML and ZIP archive technologies, Open XML is an open standard for managing office documents.
  • It offers a standardized approach to represent different Office document components, making it simpler to create, read, and alter them programmatically.

NPOI's salient attributes include: NPOI offers APIs to create, alter, and read Excel spreadsheets, making it a popular choice for working with Excel files (XLSX format). You can use cells, formulas, formatting, and other things.

Note: Make sure the EPPlus library has been installed using NuGet first

Support for Word and PowerPoint: NPOI offers the same manipulation capabilities when working with Word documents (DOCX format) and PowerPoint presentations (PPTX format).

Cross-Platform: NPOI was created in C# and is open-source; it may be used in Windows and non-Windows systems.

  • NPOI is independent of Microsoft Office. Thus you don't need to install it on the computer where you use it.
  • This is especially helpful in server contexts where there might be better ideas than installing Office.

Flexibility: For working with Office documents, NPOI offers a versatile API. You can edit already-existing documents, create new ones from scratch, and extract data from them.

Community and documentation: NPOI has a vibrant community that supports and contributes to its growth.

  • To assist you in getting started, materials are offered, including tutorials, examples, and documentation.
  • For developers who need to automate the creation and manipulation of Office documents in their apps, NPOI is a potent tool.
  •  It's especially helpful if you have to carry out these duties in settings where Microsoft Office might need to be more practical and available.

Using the NPOI Library, export and import Excel data in C#

Let's assume you wish to export a list of data to an Excel file.

Here is an illustration of data exportation to an Excel file using NPOI:

Example:

using System;

using System.Collections.Generic;

using System.IO;

using NPOI.SS.UserModel;

using NPOI.XSSF.UserModel;

namespace ExcelExportImportNPOI

{

    class Program

    {

        static void Main(string[] args)

        {

            List<Person> people = new List<Person>

            {

                new Person { FirstName = "Ram", LastName = "Deva", Age = 29 },

                new Person { FirstName = "Seetha", LastName = "Devi", Age = 21 }

            };

            string filePath = "exported_data.xlsx";

            using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))

            {

                IWorkbook workbook = new XSSFWorkbook();

                ISheet sheet = workbook.CreateSheet("People");

                int rowIndex = 0;

                IRow headerRow = sheet.CreateRow(rowIndex++);

                headerRow.CreateCell(0).SetCellValue("First Name");

                headerRow.CreateCell(1).SetCellValue("Last Name");

                headerRow.CreateCell(2).SetCellValue("Age");

                for each (var person in people)

                {

                    IRow dataRow = sheet.CreateRow(rowIndex++);

                    dataRow.CreateCell(0).SetCellValue(person.FirstName);

                    dataRow.CreateCell(1).SetCellValue(person.LastName);

                    dataRow.CreateCell(2).SetCellValue(person.Age);

                }

                workbook.Write(fs);

            }

            Console.WriteLine("Data exported to Excel successfully.");

        }

    }

    public class Person

    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Age { get; set; }

    }

}

Output:

The program will generate an Excel file called "exported_data.xlsx" in the same directory as the program file.

The "People" worksheet in the Excel file will have the following information on it:

Export and Import Excel Data in C#

The program will produce the message "Data exported to Excel successfully." to the terminal once the data has been successfully written to the Excel file.

Export and Import Excel Data in C#

Before executing the program, please verify that the NPOI library is properly set up and referenced in your project. The NPOI and NPOI.For this program to work, OOXML NuGet packages must be included in your project.

Excel Data Import:

Use a similar method to import data into NPOI from an Excel file.

An illustration of how to read data from an Excel file is shown below:

Example:

using System;

using System.Collections.Generic;

using System.IO;

using NPOI.SS.UserModel;

using NPOI.XSSF.UserModel;

namespace ExcelExportImportNPOI

{

    class Program2

    {

        static void Main(string[] args)

        {

            string filePath = "exported_data.xlsx";

            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))

            {

                IWorkbook workbook = new XSSFWorkbook(fs);

                ISheet sheet = workbook.GetSheetAt(0);

                List<Person> importedPeople = new List<Person>();

                for (int row = 1; row <= sheet.LastRowNum; row++)

                {

                    IRow dataRow = sheet.GetRow(row);

                    importedPeople.Add(new Person

                    {

                        FirstName = dataRow.GetCell(0).StringCellValue,

                        LastName = dataRow.GetCell(1).StringCellValue,

                        Age = Convert.ToInt32(dataRow.GetCell(2).NumericCellValue)

                    });

                }

                for each (var person in importedPeople)

                {

                    Console.WriteLine($"Name: {person.FirstName} {person.LastName}, Age: {person.Age}");

                }

            }

        }

    }

    public class Person

    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Age { get; set; }

    }

}

Output:

The included C# program imports data from an NPOI-created Excel file, processes it, and outputs the results to the console.

The output of this program, assuming that the Excel file "exported_data.xlsx" was produced by the one you offered, will be:

Export and Import Excel Data in C#

Exporting through ClosedXML

Another package that makes it simple to create, edit, and export Excel spreadsheets is ClosedXML.

It may be installed using NuGet:

using System;

using ClosedXML.Excel;

class Program2

{

    static void Main(string[] args)

    {

        var workbook = new XLWorkbook();

        var worksheet = workbook.Worksheets.Add("People");

        worksheet.Cell("A1").Value = "First Name";

        worksheet.Cell("B1").Value = "Last Name";

        worksheet.Cell("C1").Value = "Age";

        worksheet.Cell("A2").Value = "Ram";

        worksheet.Cell("B2").Value = "Seetha";

        worksheet.Cell("C2").Value = 29;

        worksheet.Cell("A3").Value = "Devuda";

        worksheet.Cell("B3").Value = "Smitha";

        worksheet.Cell("C3").Value = 26;

        workbook.SaveAs("exported_data.xlsx");

        Console.WriteLine("Data exported to Excel successfully.");

    }

}

Output:

The included C# program creates an Excel file, adds data, and then saves it using the ClosedXML library.

The program will generate an Excel file called "exported_data.xlsx" in the same directory as the program file.

 The "People" worksheet in the Excel file will have the following information on it:

Export and Import Excel Data in C#

The program will produce the message "Data exported to Excel successfully." to the terminal once the data has been successfully written to the Excel file.

Before executing the program, please verify that the ClosedXML library is properly set up and referenced in your project. This program assumes that your project already contains the required ClosedXML NuGet package.

Export and Import Excel Data in C#

In the same directory as the program file, an Excel file called "exported_data.xlsx" is generated when you run this program.

Using ExcelDataReader import

A library called ExcelDataReader makes it possible to read Excel files without using Microsoft Office.

It may be installed using NuGet:

using System;

using System.Data;

using System.IO;

using ExcelDataReader;

class Program3

{

    static void Main(string[] args)

    {

        using (var stream = File. Open("exported_data.xlsx," FileMode.Open, FileAccess.Read))

        {

            using (var reader = ExcelReaderFactory.CreateReader(stream))

            {

                do

                {

                    while (reader. Read())

                    {

                        string firstName = reader.GetString(0);

                        string lastName = reader.GetString(1);

                        int age = reader.GetInt32(2);

                        Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}");

                    }

                } while (reader.NextResult());

            }

        }

    }

}

Both examples have been simplified to give you a fundamental understanding of dealing with the ClosedXML and ExcelDataReader libraries. The code should be modified to meet your needs, and error checks should be handled correctly.

Output:

Export and Import Excel Data in C#

Uses of Excel Export and Import:

Excel Data Export:

Data Reporting: Business analytics reports, charts, and visualizations are frequently created by exporting data to Excel.

Data backup: Excel files can be used as a basic backup solution for storing data outside of databases or other systems.

Data sharing: Users can share information with people who might not have direct access to a database by exporting data to Excel.

Data analysis: Using Excel's built-in capabilities can be simpler when data is exported to Excel.

Bulk Data Entry: Users can export data to Excel, make changes, and reimport the revised data into the program.

Making Templates: Users can utilize exported Excel files as templates to fill up data before importing.

Custom Reporting: Users have the option to export data and alter it in Excel to produce reports that are uniquely formatted.

Data Import into Excel:

Data migration: When transferring data from outdated systems to new applications, Excel imports might be helpful.

Data Integration: Data from diverse sources can be integrated into a single system or database by importing the data.

Bulk Data Loading: applications can use Excel import to more quickly load massive amounts of data than human data entering.

User Data Entry: Users can prepare data in Excel and import it into the program, which saves the time by eliminating the need for manual data entry.

Data validation: Importing data enables validation checks before updating the application's database.

Workflow automation: Data imports can start automatic procedures like producing reports or notifying users.

An application's flexibility and interoperability are improved by exporting and importing Excel data. They give consumers a comfortable data management interface and enable seamless data transmission between various systems. Nevertheless, managing fault situations and guaranteeing data consistency across these procedures is crucial.