Skip to main content

How to Convert Excel to CSV and CSV to Excel in C#

In data processing and reporting workflows, exchanging data between Excel and CSV is a common requirement. CSV is lightweight, easy to parse, and ideal for integration with databases or web services, while Excel provides rich formatting and formulas.

Using C#, you can handle conversions efficiently, ensuring data integrity, proper formatting, and flexibility for automation. This article covers practical methods, from basic conversions to batch processing and advanced customization.

Getting Started: Installing the Required Library

Before diving into code, you need to install a library that supports handling Excel files. In this article, we use Free Spire.XLS for .NET. It is a free Excel library that supports modern Excel features and includes built-in methods for converting Excel to CSV and vice versa.

Installation via NuGet

Open your project in Visual Studio and run:

Install-Package FreeSpire.XLS

Verifying the Installation

To ensure the library is installed correctly, create a simple console app:

using Spire.Xls;

class Program
{
    static void Main()
    {
        Workbook workbook = new Workbook();
        System.Console.WriteLine("Spire.XLS is installed successfully.");
    }
}

If this runs without errors, you’re ready to start converting files.

Converting Excel to CSV

Exporting Excel worksheets to CSV is the most common task, especially when preparing data for ETL processes, web applications, or CSV-based reporting.

Basic Conversion

This example shows how to convert the first worksheet in an Excel file to a CSV file using UTF-8 encoding.

using Spire.Xls;
using System.Text;

namespace ConvertExcelToCsv
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            Worksheet sheet = workbook.Worksheets[0];
            sheet.SaveToFile("ExcelToCSV.csv", ",", Encoding.UTF8);

            workbook.Close();
        }
    }
}

This approach preserves text, numbers, and basic formatting. CSV files created this way can be opened by Excel, databases, or any CSV-compatible tool.

Customizing CSV Output

Sometimes, you may want more control over how Excel data is exported:

  • Choose a specific delimiter (comma, semicolon, tab, etc.)

  • Handle special characters or non-English text

  • Control numeric formatting

Spire.XLS allows you to specify delimiter and encoding explicitly, which helps prevent issues with different regional settings.

Converting CSV Back to Excel

Importing CSV into Excel is equally straightforward. You can adjust formatting, auto-fit rows and columns, and handle numeric/text conflicts.

using Spire.Xls;

namespace ConvertCsvToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"ExcelToCSV.csv", ",", 1, 1);

            Worksheet sheet = workbook.Worksheets[0];
            CellRange usedRange = sheet.AllocatedRange;
            usedRange.IgnoreErrorOptions = IgnoreErrorType.NumberAsText;
            usedRange.AutoFitColumns();
            usedRange.AutoFitRows();

            workbook.SaveToFile("CSVToExcel.xlsx", ExcelVersion.Version2013);
            workbook.Close();
        }
    }
}

This method ensures that CSV data is imported cleanly while applying basic formatting for readability.

Advanced Scenario: Batch Conversion

In real-world applications, you may need to process multiple files automatically. For example, converting all Excel files in a folder to CSV can be done with a few lines of code:

using Spire.Xls;
using System.IO;
using System.Text;

class BatchConvert
{
    static void Main()
    {
        string inputFolder = @"C:\InputExcels\";
        string outputFolder = @"C:\OutputCSVs\";

        foreach (string filePath in Directory.GetFiles(inputFolder, "*.xlsx"))
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(filePath);

            Worksheet sheet = workbook.Worksheets[0];
            string fileName = Path.GetFileNameWithoutExtension(filePath);

            sheet.SaveToFile(Path.Combine(outputFolder, fileName + ".csv"), ",", Encoding.UTF8);
            workbook.Close();
        }

        System.Console.WriteLine("Batch conversion completed.");
    }
}

Batch processing is ideal for:

  • Automated ETL pipelines

  • Daily or weekly report exports

  • Preparing large datasets for analytics

Things to Keep in Mind

While converting Excel and CSV files is straightforward, a few practical details can affect results:

1. Encoding Issues

Incorrect encoding may cause non-English characters to appear garbled. UTF-8 is recommended for most scenarios, but UTF-16 may be needed for legacy systems.

2. Numeric Values vs. Text

Excel may interpret numbers as text when importing CSV. Use IgnoreErrorOptions to avoid errors, especially for formulas or IDs stored as text.

3. Resource Management

Always call Close() on Workbook objects to free memory, especially in loops or batch processing. Otherwise, memory usage can increase significantly.

4. Column Widths and Row Heights

CSV files do not preserve Excel formatting. If you need readable output when converting back to Excel, use AutoFitColumns() and AutoFitRows() to maintain visual clarity.

Conclusion

Converting between Excel and CSV in C# is simple and reliable with Spire.XLS. Whether you’re handling single files or processing entire folders, these methods ensure data integrity, proper formatting, and efficiency.

By combining basic conversions, custom settings, and batch processing, developers can automate workflows, integrate data pipelines, and handle reporting tasks with minimal effort.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...