Published November 23, 2023
How to Write A CSV File in C#
Creating and writing CSV files using the C# .NET framework is a fundamental skill for developers dealing with public string row data manipulation and data storage format. Whether you're building applications that handle all the rows of user inputs such as public class student, convert new list objects, manage database records for student class, or process large file datasets, the ability to efficiently write data values in CSV is crucial using the var writer and new Streamwriter class. C#
This introductory paragraph sets the stage for exploring the key concepts and techniques involved in writing a new CSV file data in C# such as var writer, emphasizing the practical significance of this process in diverse software development scenarios. Whether you're a seasoned C#
In this article, we will see how to write CSV files using a C# library named IronXL in a new project.
How to Write a CSV File
Install the C# library for writing into a CSV File.
Use
WorkBook.Create
to create a new workbook.Create a new worksheet using
workBook.CreateWorkSheet().
Add values to individual cells using
workSheet["cell name"].Value
usingvar
.- Save the spreadsheet as a CSV file using the
SaveAs
method.
IronXL
IronXL emerges as a beacon of efficiency for C# developers seeking a seamless and powerful solution for writing data to CSV files as compared to the CsvHelper NuGet package. In the dynamic landscape of software development, the ability to handle and manipulate data is paramount, and IronXL steps up to the plate with its robust set of tools tailored for C#
This article delves into the features and methodologies that make IronXL the go-to choice for C# developers looking to enhance the process of writing data to CSV files, striking the perfect balance between simplicity and precision.
Create a New Visual Studio Project
To begin using an existing library IronXL, the initial step involves either creating a fresh Visual Studio C# project or loading an existing one. Here are the instructions for generating a new project in Visual Studio
Open Visual Studio and navigate to the "File" menu. A dropdown menu will be displayed; within this menu, select "New." This action will reveal another side menu.
In the side menu, locate and click on "Project." This will open a new window. Within this window, utilize the search bar to find "Console Application." Choose the option associated with C# and proceed by clicking the "Next" button.
A configuration window will appear next. Enter the project name, specify the project location, and click on the "Next" button.
The final window will emerge. Here, pick the target framework and initiate the project creation process by clicking on "Create."
Installing CSV Library IronXL
Now that you've set up the project, it's time to incorporate the IronXL C# library. Follow these steps to install IronXL in your C#
- In Visual Studio, navigate to Tools. A dropdown menu will emerge—select the NuGet Package Manager from this menu.
Within the NuGet Package Manager, choose the NuGet Package Manager for Solutions from the side menu that unfolds.
A new window will pop up. Head to the browser tab within this window, and in the search bar, type "IronXL." You'll see a list of IronXL packages; opt for the latest one and proceed to click on the Install button.
Writing CSV Files Using IronXL
Write data into CSV file using C# CSV library IronXL such as public string firstname
, public string lastname
. In this section, we will create a new CSV file and write data in it. The following example uses the IronXL library to create a simple receipt in a CSV file. Let's break down the program code step by step class Program.
Importing IronXL and System.Linq
using IronXL;
using System.Linq;
public class Program{
static void Main() {
using IronXL;
using System.Linq;
public class Program{
static void Main() {
Imports IronXL
Imports System.Linq
Public Class Program
Shared Sub Main()
These lines import the necessary classes and functionalities from the IronXL library for working with Excel files and the LINQ
extension methods from the System.Linq
namespace within the static void main.
Creating a Workbook
and Worksheet
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");
Dim workBook As WorkBook = WorkBook.Create()
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Receipt")
This code creates a new Excel workbook (WorkBook
) and a worksheet (WorkSheet
) within that workbook named "Receipt."
Adding Headers
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Price";
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Price";
workSheet("A1").Value = "Product"
workSheet("B1").Value = "Price"
These lines set the header row for the columns in the first row of the worksheet.
Populating Item Information
workSheet["A2"].Value = "Item 1";
workSheet["B2"].DoubleValue = 20.10;
workSheet["A3"].Value = "Item 2"; //next row
workSheet["B3"].DoubleValue = 15.50;
workSheet["A4"].Value = "Item 3";
workSheet["B4"].DoubleValue = 10.25;
workSheet["A2"].Value = "Item 1";
workSheet["B2"].DoubleValue = 20.10;
workSheet["A3"].Value = "Item 2"; //next row
workSheet["B3"].DoubleValue = 15.50;
workSheet["A4"].Value = "Item 3";
workSheet["B4"].DoubleValue = 10.25;
workSheet("A2").Value = "Item 1"
workSheet("B2").DoubleValue = 20.10
workSheet("A3").Value = "Item 2" 'next row
workSheet("B3").DoubleValue = 15.50
workSheet("A4").Value = "Item 3"
workSheet("B4").DoubleValue = 10.25
These lines populate the worksheet with information about three items, including their names and price columns for users.
Calculating Total Price
var range = workSheet["B2:B4"];
decimal sum = range.Sum(); //sum of rows
var range = workSheet["B2:B4"];
decimal sum = range.Sum(); //sum of rows
Dim range = workSheet("B2:B4")
Dim sum As Decimal = range.Sum() 'sum of rows
Using LINQ, this code calculates the sum of the prices from cells B2 to B4 using the var
range. The sum is stored in the sum
variable.
Displaying and Updating Total in the Worksheet
System.Console.WriteLine(sum); //write to console
workSheet["B5"].Value = sum;
System.Console.WriteLine(sum); //write to console
workSheet["B5"].Value = sum;
System.Console.WriteLine(sum) 'write to console
workSheet("B5").Value = sum
The sum is printed to the console, and the total is updated in cell B5 of the worksheet.
Saving the Workbook as a CSV File
workBook.SaveAs("receipt.csv");
}
}
workBook.SaveAs("receipt.csv");
}
}
workBook.SaveAs("receipt.csv")
}
}
Finally, the entire workbook is saved as a CSV file named "receipt.csv."
In summary, this code creates a basic receipt in an Excel worksheet using IronXL, calculates the total price, prints it to the console, and then saves the workbook output as a CSV file. The receipt includes columns for "Product" and "Price," and it calculates the total price based on the individual item prices.
Conclusion
This comprehensive article underscores the significance of writing CSV files in C# and elucidates the process using the IronXL library. It emphasizes the fundamental nature of this skill in diverse data-centric applications and showcases IronXL's prowess in simplifying and optimizing data manipulation tasks within the C# ecosystem. The step-by-step approach, from project setup to utilizing IronXL to create a receipt and save it as a CSV file, provides developers with a practical understanding of the seamless integration between C#
By offering versatility and efficiency, IronXL emerges as a valuable tool for C# developers seeking to enhance their program and ability to handle and export data in the ubiquitous CSV format, making it a crucial asset for various software development scenarios.
For the complete tutorial on writing into a CSV file visit here. The code example for creating a CSV file can be found at the following link.