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.
Top comments (0)