Overview

In the world of data management, handling Comma Separated Values (CSV) files is a common requirement. These files are widely used for storing tabular data such as spreadsheets or databases due to their simplicity and easy readability. The ability to merge and split CSV files programmatically can save time and streamline workflows, especially when dealing with large volumes of data.

This article provides a step-by-step guide on how to merge and split CSV files using the GroupDocs.Merger for .NET library.

How to Merge CSV Files

Merging multiple CSV files into a single document can significantly simplify data handling and reporting. In C#, the GroupDocs.Merger for .NET library makes this process straightforward and efficient, eliminating the need for manual data manipulation. Below are the key steps to merge CSV files using C#:

  1. Load your source CSV file: Create an instance of the Merger class, passing the file path of the first CSV file as a parameter.
  2. Add additional CSV files: Use the Join method to add other CSV files that you want to merge into the first document.
  3. Save the merged result: Call the Save method to write the combined data to a new CSV file.

Here’s an example illustrating these steps:

// Import necessary namespaces
using System;
using System.IO;

namespace GroupDocs.Merger.Examples.CSharp.BasicUsage
{
    /// <summary>
    /// This example demonstrates how to merge multiple CSV files into a single file.
    /// </summary>
    internal static class MergeCsv
    {
        public static void Run()
        {
            Console.WriteLine("=======================================================================");
            Console.WriteLine("Example Basic Usage: MergeCsv");
            Console.WriteLine();

            // Define the output folder and file name
            string outputFolder = Constants.GetOutputDirectoryPath();
            string outputFile = Path.Combine(outputFolder, "merged.csv");
            
            // Load the source CSV file using the Merger class
            using (var merger = new GroupDocs.Merger.Merger(Constants.SAMPLE_CSV))
            {
                // Add another CSV file to merge
                merger.Join(Constants.SAMPLE_CSV_2);
                
                // Merge CSV files and save the result to 'merged.csv'
                merger.Save(outputFile);
            }

            Console.WriteLine("CSV files merge completed successfully.");
            Console.WriteLine($"Check output in {outputFolder}");
        }
    }
}

In this code snippet:

  • The Merger class is instantiated with the path of the first CSV file.
  • The Join method is called to include another CSV file.
  • The final merged file is saved with the Save method.

How to Split CSV Files

Splitting a large CSV file into smaller, manageable pieces is equally essential for data governance and analysis. This is especially useful when you need to isolate data points or manage file sizes for processing. With the GroupDocs.Merger for .NET library, splitting CSV files is as easy as merging. Below are the steps for splitting a CSV file into separate documents:

  1. Define the output format: Specify the naming convention for the output files (for example, line_1.csv, line_2.csv, etc.).
  2. Use the Split method: Apply this method from the Merger class, alongside the appropriate options that dictate how the splitting should occur.
  3. Manage output: After splitting, you will have each line or specified segment as its own separate file.

Here’s how you can achieve this with C#:

// Import necessary namespaces
using System;
using System.IO;
using GroupDocs.Merger.Domain.Options;

namespace GroupDocs.Merger.Examples.CSharp.BasicUsage
{
    /// <summary>
    /// This example demonstrates how to split a CSV file into separate documents.
    /// </summary>
    public class SplitCsv
    {
        public static void Run()
        {
            Console.WriteLine("=======================================================================");
            Console.WriteLine("Example Basic Usage: SplitCsv");
            Console.WriteLine();

            // Define the path to the CSV file
            string filePath = Constants.SAMPLE_CSV;
            // Define the output path with a naming pattern
            string filePathOut = Path.Combine(Constants.GetOutputDirectoryPath(), "line_{0}.csv");

            // Create split options to define how to split
            TextSplitOptions splitOptions = new TextSplitOptions(filePathOut, new int[] { 1, 2, 3 });

            using (Merger merger = new Merger(filePath))
            {
                // Split the CSV file according to the specified options
                merger.Split(splitOptions);
            }

            Console.WriteLine("Source document was split successfully.");
            Console.WriteLine($"Check output at {filePathOut}.");
        }
    }
}

In this example:

  • The script segments the data based on specified line numbers and saves each segment as a new CSV file.
  • The TextSplitOptions class allows for flexible configuration of how the split occurs.

See also

For more information and resources, check out the following links:

You can download a free trial from releases.groupdocs.com and obtain a temporary license here to try our library without restrictions.

Code Examples

To give you a better understanding of how to effectively use the GroupDocs.Merger for .NET library, here are some practical examples showcasing merging and splitting CSV files. These snippets can easily be adapted to fit your specific data processing needs.

Example: Merging Multiple CSV Files

This example demonstrates merging multiple CSV files into a single file by using the GroupDocs.Merger package. Ensure that the paths to your sample files are correctly set.

using System;
using System.IO;

namespace GroupDocs.Merger.Examples.CSharp.BasicUsage
{
    internal static class MergeMultipleCsvFiles
    {
        public static void Run()
        {
            Console.WriteLine("Merging multiple CSV files.");

            // Define the output folder and output file name for the merged CSV
            string outputFolder = Constants.GetOutputDirectoryPath();
            string outputFile = Path.Combine(outputFolder, "merged_result.csv");
            
            // Start merging process
            using (var merger = new GroupDocs.Merger.Merger(Constants.SAMPLE_CSV))
            {
                merger.Join(Constants.SAMPLE_CSV_2); // Add second CSV file
                merger.Join(Constants.SAMPLE_CSV_3); // Add third CSV file
                merger.Save(outputFile); // Save combined result
            }

            Console.WriteLine($"Successfully merged CSV files into {outputFile}");
        }
    }
}

Example: Splitting a CSV File into Individual Lines

In this snippet, we will split a large CSV file into multiple smaller files, each containing specified lines. This can be useful for processing large datasets or distributing workload.

using System;
using System.IO;
using GroupDocs.Merger.Domain.Options;

namespace GroupDocs.Merger.Examples.CSharp.BasicUsage
{
    public class SplitCsvToLines
    {
        public static void Run()
        {
            Console.WriteLine("Splitting a CSV file into individual line files.");

            // Specify the path of the source CSV file
            string filePath = Constants.SAMPLE_CSV;
            // Define output file naming pattern for split result
            string outputFilePath = Path.Combine(Constants.GetOutputDirectoryPath(), "line_{0}.csv");

            // Set up split options based on desired line numbers
            TextSplitOptions splitOptions = new TextSplitOptions(outputFilePath, new int[] { 1, 2, 3 });

            using (Merger merger = new Merger(filePath))
            {
                merger.Split(splitOptions); // Split the file based on options
            }

            Console.WriteLine($"Successfully split the source document into individual line files.");
        }
    }
}

See also

For more information and technical resources, check out the links below:

Free Trial and Temporary License Information

You can download a free trial version of GroupDocs.Merger from releases.groupdocs.com. For those considering a more extensive evaluation, you can also acquire a temporary license from here. This temporary license allows you to test our library without any limitations, ensuring you can fully explore its capabilities.