How to Export File to CSV in C#

1.0 Introduction

Spreadsheet software like Microsoft Excel is available for Windows, macOS, iOS, Android, and iPadOS. Lessons on pivot tables, graphing instruments, mathematical ideas, and the macro programming language Visual Basic for Applications (VBA) are all included in the curriculum. Excel is one of the apps included in the Microsoft 365 software suite. Spreadsheets such as Excel organize data manipulations, including arithmetic calculations, using a grid of cells arranged in numbered rows and letter-named columns. It offers integrated capabilities to meet technical, statistical, and financial domain requirements. In addition to showing data as charts, line graphs, and histograms, it has a limited three-dimensional graphical presentation. Data can be segmented to show how various factors affect it from various perspectives.

This article will contrast and compare various methods that .NET technologies can interface programmatically with Microsoft Excel documents using one of the most well-known libraries, IronXL. Moreover, it will create a setting for writing, reading, and exporting Excel spreadsheets to CSV files.

1.1 What is Dot Net Framework?

Microsoft created the proprietary .NET Framework, a software framework that is mostly compatible with Microsoft Windows. It served as the main Common Language Infrastructure (CLI) implementation until the cross-platform.NET project took its place. It offers language compatibility across a number of different programming languages and comes with a sizable class library called the Framework Class Library (FCL).

1.2 What is CSV?

A text file format called "comma-separated values" divides values into separate columns using commas. Tabular data is stored in plain text in a CSV format file, where each line typically corresponds to a single data record. In the CSV file, each record has the same number of fields, which are separated by commas.

2.0 IronXL Library Features

Microsoft Excel documents can be read and converted to CSV files using the IronXL for .NET C# Excel library. Without installing Microsoft Office or Microsoft.Office.Interop.Excel, users can utilize IronXL, a stand-alone.NET software library. It is capable of reading several spreadsheet formats.

IronXL's simple C# API makes it easy to read, edit, and produce Excel spreadsheets in a .NET context. IronXL provides complete support for Xamarin, Linux, macOS, Azure, .NET Core, and .NET Framework.

  • IronXL, a C# library compatible with both .NET Core and .NET Framework, is one of the best for Excel spreadsheets.
  • IronXL supports almost every .NET Framework, including console, Windows Forms, and web applications.
  • IronXL is compatible with Windows, macOS, and Linux operating systems.
  • IronXL makes it simple and quick to access Excel files.
  • IronXL can read a wide variety of Excel file types, including XLSX, CSV, XLS, XSLT, TSV, XLSM, and others. Functions for importing, updating, and exporting datasets and data tables are only a few of our numerous options.
  • IronXL can generate calculations for the Excel spreadsheet.
  • IronXL supports a variety of data types for Excel columns, including text, dates, integers, currencies, formulas, and percentages.
  • IronXL supports text, numbers, dates, currencies, percentages, formulas, and other Excel column data types.

To know how to export data into Excel refer to the link here.

3.0 Creating a New Project in Visual Studio

We need to open Visual Studio and create a .NET project before we can use the IronXL library. Visual Studio can be used in any version, though the most recent version is advised. Depending on your needs, you can construct a project template or an application similar to Windows Forms. To keep things simple, I'll be using the Console Application for this example.

How to Export File to CSV in C#: Figure 1 - Open Visual Studio, go to File menu and select New Project. From the various .Net project templates choose the Console App.

Enter the project's location and name after that.

How to Export File to CSV in C#: Figure 2 - Enter the Project name and set the project's location path and .NET Framework. Then click on the Create button to continue.

The Framework drop-down menu can be used to choose a .NET Framework. We will be using the Dot Net Framework 4.7 for this project. Next, click on the "Create" button.

The program.cs file will open when the application generates the solution, allowing you to enter the code and build/run the program.

How to Export File to CSV in C#: Figure 3 - The Program.cs file will open once the Console Application project is successfully created.

To test the code, we can now add the IronXL library.

Install the IronXL library, since it is required for the next fix. To do this, enter the following command into the NuGet Package Manager Console:

Install-Package IronXL.Excel

How to Export File to CSV in C#: Figure 4 - For installing the IronXL library, you can use the Package Manager Console and enter the given command: Install-Package IronXL.Excel

Another option is to use the NuGet Package Manager to look for the package "IronXL". We can choose the necessary package to download from this list of all the NuGet packages connected to IronXL.

How to Export File to CSV in C#: Figure 5 - Another way to install IronXL is by using the NuGet Package Manager for Solutions. Enter ironxl in the search box to search for the IronXL library.

4.0 Export to CSV file

IronXL makes it simple and quick to create string arrays to CSV files. Writing CSV files is made simpler as a result. We need to include the IronXL namespace first, as shown in the code screenshot below. We can use IronXL's classes and methods in our code once it has been presented.

How to Export File to CSV in C#: Figure 6 - Include the IronXL namespace within your program file using the command using IronXL. This ensures that we can use all the classes and methods of the IronXL library into our code.

Excel files can be created with IronXL and then turned into workbook objects. We have several options for working with them once they are objects. The following example of code generates an Excel file by converting an array string into an Excel worksheet.

using IronXL;
using IronXL.Options;
using System.Data;
static void Main ( string [ ] args ) { 
string[] Students = {"AAA","BBB","CCC","DDD","EEE","FFF" };
var workbook = WorkBook.Create(ExcelFileFormat.XLS);
var writer = workbook.DefaultWorkSheet;
int rowCount = 1;
foreach(var student in Students)
{
    writer["A" + (rowCount)].Value = rowCount.ToString();
    writer["B" + (rowCount)].Value = student.ToString();
    rowCount++;
}
workbook.SaveAsCsv("Sample.csv", ";");
//or
var stream= workbook.ToStream();
}
using IronXL;
using IronXL.Options;
using System.Data;
static void Main ( string [ ] args ) { 
string[] Students = {"AAA","BBB","CCC","DDD","EEE","FFF" };
var workbook = WorkBook.Create(ExcelFileFormat.XLS);
var writer = workbook.DefaultWorkSheet;
int rowCount = 1;
foreach(var student in Students)
{
    writer["A" + (rowCount)].Value = rowCount.ToString();
    writer["B" + (rowCount)].Value = student.ToString();
    rowCount++;
}
workbook.SaveAsCsv("Sample.csv", ";");
//or
var stream= workbook.ToStream();
}
Imports IronXL
Imports IronXL.Options
Imports System.Data
Shared Sub Main(ByVal args() As String)
Dim Students() As String = {"AAA", "BBB", "CCC", "DDD", "EEE", "FFF"}
Dim workbook = WorkBook.Create(ExcelFileFormat.XLS)
Dim writer = workbook.DefaultWorkSheet
Dim rowCount As Integer = 1
For Each student In Students
	writer("A" & (rowCount)).Value = rowCount.ToString()
	writer("B" & (rowCount)).Value = student.ToString()
	rowCount += 1
Next student
workbook.SaveAsCsv("Sample.csv", ";")
'or
Dim stream= workbook.ToStream()
End Sub
VB   C#

The aforementioned code-csv example will export an array to an Excel file. Column heads are created once an array has been constructed. We add the rows one at a time when the first column is established. We create the workbook object once the data has been added to the array string. You can add data to an Excel sheet using the workbook object, and then save it somewhere else. Our goal is to create worksheets by creating the worksheet object, which we can then add to the workbook object. We can also produce the files using the model class.

Before adding each item to the spreadsheet, we use a foreach loop to read each item from the array string. The data is saved as a CSV file using the SaveAsCsv method when all the data has been entered into the worksheet. Along with the delimiter, we can provide parameters for the file name and location. We can regard a delimiter as an optional input if one is not required. The library then assists in writing data to a new CSV file. If you want to read CSV files instead of using Microsoft Excel, you can use Notepad. We also have the ability to store data in multiple file formats, such as XLS, CSV, and XLSX, by using the Save method. Or the workbook can be turned into a stream. Then we can use the stream to write data into the required location.

OUTPUT CSV File

How to Export File to CSV in C#: Figure 7 - OUTPUT Excel file: Sample.csv

The output of the code sample that was run is seen above. The newly produced Excel sheet in the screenshot has each item of data from the string array added independently.

To know more about how to export data into CSV using IronXL, please refer to this step-by-step tutorial.

5.0 Conclusion

One of the most popular Excel add-ons is IronXL. It doesn't rely on any other outside libraries. It is self-contained and does not require the installation of Microsoft Excel. It operates via several channels.

IronXL provides a complete solution for all programmatically executed MS Excel document-related tasks. It is possible to perform calculations, sort strings or numbers, trim, add, locate and replace, merge and unmerge, save files, and more. You can define cell data types in addition to checking spreadsheet data. It lets you read and write files and makes dealing with Excel data easier.

IronXL offers a free free trial license which gives users a chance to try all its key features for free.

IronXL is available for $599 at launch. If users would like updates and help with the software, they can also choose to pay a one-year subscription charge. For an additional fee, IronXL offers protection for unlimited redistribution. To find more accurate pricing information, please visit IronXL's license page.