Spire.Office Knowledgebase Page 1 | E-iceblue

A guide to create CSV files in C#/.NET

CSV (Comma-Separated Values) files remain one of the most widely used data exchange formats in modern software development. Their simplicity, human-readability, and compatibility across different systems make them ideal for data export, import, and transformation tasks. If you’re a developer looking to create a CSV file in C#, the Spire.XLS for .NET library offers a robust, easy-to-use solution—no need for manual string manipulation or complex Excel interop.

In this guide, we’ll walk you through everything you need to know to create or write CSV files in C# with Spire.XLS, from basic CSV creation to advanced Excel to CSV conversion.


Why Choose Spire.XLS to Create CSV?

Spire.XLS for .NET is a professional Excel API that provides extensive spreadsheet manipulation capabilities, including robust CSV support. Here's why developers prefer it:

  • No Excel Dependency: Unlike Microsoft Office Interop, Spire.XLS works independently of Excel, eliminating dependency issues in production environments.
  • Simplified API: Intuitive methods to create, populate, and save CSV files without low-level file handling.
  • Seamless Excel-CSV Conversion: Export existing Excel files (XLS/XLSX) to CSV with zero manual parsing.
  • Customization: Control delimiters, encodings, and formatting to meet specific CSV requirements.

Getting Started with Spire.XLS

To get started, you need to:

  • Have Visual Studio installed.
  • Install the Spire.XLS for .NET library via NuGet:
    • Visual Studio GUI: Right-click your project → Manage NuGet Packages → Search for Spire.XLS → Install.
    • Package Manager Console:
PM> Install-Package Spire.XLS

Create a Basic CSV File in C#

Here's a straightforward example demonstrating how to create a CSV file from scratch:

using System.Text;
using Spire.Xls;

namespace CreateCSV
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Create a new Excel workbook
            Workbook workbook = new Workbook();

            // 2. Add a worksheet (CSV is based on a single worksheet)
            Worksheet worksheet = workbook.Worksheets.Add("ProductData");

            // 3. Define header row
            worksheet.Range["A1"].Value = "ProductID";
            worksheet.Range["B1"].Value = "ProductName";
            worksheet.Range["C1"].Value = "Price";
            worksheet.Range["D1"].Value = "InStock";

            // 4. Populate sample data rows
            worksheet.Range["A2"].Value2 = 1001;
            worksheet.Range["B2"].Value = "Laptop XPS 15";
            worksheet.Range["C2"].Value2 = 1299.99;
            worksheet.Range["D2"].Value = "YES";

            worksheet.Range["A3"].Value2 = 1002;
            worksheet.Range["B3"].Value = "Wireless Mouse";
            worksheet.Range["C3"].Value2 = 29.99;
            worksheet.Range["D3"].Value = "NO";

            worksheet.Range["A4"].Value2 = 1003;
            worksheet.Range["B4"].Value = "Mechanical Keyboard";
            worksheet.Range["C4"].Value2 = 89.99;
            worksheet.Range["D4"].Value = "YES";

            // 5. Save as CSV
            worksheet.SaveToFile("ProductList.csv", ",", Encoding.UTF8);
            workbook.Dispose();
        }
    }
}

How It Works:

  • Workbook Initialization: Start by creating a Workbook object (Spire.XLS’s core object for Excel/CSV operations).
  • Worksheet Creation: Add a worksheet to write data as CSV files map to a single worksheet.
  • Data Population: Spire.XLS provides two properties for cell values to handle data types correctly:
    • Value: Used for text/string data.
    • Value2: Used for booleans, strings, numbers, dates, etc.
  • Save as CSV: The SaveToFile method converts the worksheet to a CSV file.

Output:

The generated ProductList.csv will look like this:

Create a simple CSV file from scratch using C#

If you need to read a CSV file, refer to: Read CSV Files in C#: Basic Parsing & DataTable Conversion


Create a CSV from a List of Objects with C#

In real projects, data usually comes from collections (e.g., List<T>). This example populates a CSV from a list of Product objects:

using System.Collections.Generic;
using System.Text;
using Spire.Xls;

namespace CreateCSVFromList
{
    // Define a custom Product class
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public bool InStock { get; set; }
    }

    class Program
    {
        static void Main(string[] args)

        {
            // Step 1: Prepare structured list data
            List<Product> productList = new List<Product>()
            {
                new Product { ID = 1001, Name = "Laptop", Price = 999.99m, InStock = true },
                new Product { ID = 1002, Name = "T-shirt", Price = 19.99m, InStock = false  },
                new Product { ID = 1003, Name = "Coffee Mug", Price = 8.99m, InStock = false  },
                new Product { ID = 1004, Name = "Wireless Mouse", Price = 24.99m, InStock = true  }
            };

            // Step 2: Create Spire.XLS objects
            Workbook workbook = new Workbook();
            Worksheet worksheet = workbook.Worksheets[0];

            // Step 3: Write CSV header (Row 1)
            worksheet.Range[1, 1].Text = "ID";
            worksheet.Range[1, 2].Text = "Name";
            worksheet.Range[1, 3].Text = "Price";
            worksheet.Range[1, 4].Text = "InStock";

            // Step 4: Fill structured data into worksheet (start from Row 2)
            for (int i = 0; i < productList.Count; i++)
            {
                int rowNum = i + 2;
                Product product = productList[i];

                // Assign data to cells
                worksheet.Range[rowNum, 1].NumberValue = product.ID; // Numeric type
                worksheet.Range[rowNum, 2].Text = product.Name;     // String type
                worksheet.Range[rowNum, 3].NumberValue = (double)product.Price; // Decimal → Double
                worksheet.Range[rowNum, 4].BooleanValue = product.InStock; // Boolean value
            }

            // Step 5: Save as CSV
            string csvPath = "structured_products.csv";
            worksheet.SaveToFile(csvPath, ",", Encoding.UTF8);
            workbook.Dispose();
        }
    }
}

Key Code Explanations:

  • Workbook/Worksheet: Spire.XLS uses Workbook to manage worksheets, even for CSV.
  • Cell Indexing: Spire.XLS uses 1-based indexing (rows/columns start at 1, not 0).
  • Data Type Handling:
    • Use .Text for string values (e.g., product name/category).
    • Use .NumberValue for numeric values (int/decimal/double).
    • Use .BooleanValue for Boolean values.

Output CSV:

Create a CSV file from a list using C#


Create a CSV File from Excel in C#

A common real-world scenario is converting Excel to CSV. This example loads an existing Excel file (.xls or .xlsx) and exports its first worksheet to a CSV file.

using System.Text;
using Spire.Xls;

namespace ExcelToCSV
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Load an existing Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Test.xlsx");

            // 2. Select the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            // 3. Save worksheet as CSV
            worksheet.SaveToFile("ExcelToCSV.csv", ",", Encoding.UTF8);
            workbook.Dispose();

        }
    }
}

Excel to CSV Conversion Result:

Convert Excel to CSV in C#

Customization Tip: You can change the delimiter and encoding parameters of the SaveToFile() method to meet regional requirements.


Conclusion​

Creating a CSV file in C# with Spire.XLS for .NET is fast, reliable, and requires minimal code compared to manual file writing. Whether you’re building a basic CSV from scratch, mapping collections to CSV, or converting from Excel files, this guide offers detailed, actionable instructions to streamline your workflow.

With Spire.XLS, you can generate CSV file in C# easily. For more Excel or CSV-related tasks in .NET development, visit the online documentation.


FAQs (Common Questions)

Q1: How to handle non-English characters in CSV?

A: Use Encoding.UTF8 or Encoding.Unicode in SaveToFile to preserve non-ASCII characters.

Q2: Can I create a CSV with multiple worksheets?

A: No—CSV is a single-sheet format. For multiple datasets, create separate CSV files or merge sheets into one before saving.

Q3: How do I save a CSV without a header row?

A: Simply skip writing the header row in the worksheet and start populating data from the first row.

Q4: Is Spire.XLS free?

A: Spire.XLS offers a free version with limitations. Or you can request a trial license here to test its full features without restrictions.

To print Word, Excel, PowerPoint, PDF, and other document types, Spire.Printing is used together with the corresponding Spire.Office document libraries—Spire.Doc, Spire.XLS, Spire.Presentation, and Spire.PDF (especially the .NET Standard version)—to load the source files, save them into IPrintDocumentStream, and send them to the printer.

To print Word, Excel, PowerPoint, PDF, and other document types, Spire.Printing is used together with the corresponding Spire.Office document libraries—Spire.Doc, Spire.XLS, Spire.Presentation, and Spire.PDF (especially the .NET Standard version)—to load the source files, save them into IPrintDocumentStream, and send them to the printer.

Page 1 of 331
page 1