简体   繁体   中英

Combining csv files horizontally

I have a little project that I want to complete in C#, I'm no expert but I haven't been able to find any other solutions for what I'm trying to do so maybe I just don't know what to look for.

I have several csv files set out like this;

  | AColumn  | BColumn
--+----------+---------
1 | Title    |
--+----------+---------
2 | Year     |
--+----------+---------
3 | Heading1 | Heading2
--+----------+---------
4 | DATA1    | DATA2

What I'd like to do (and I'm not sure if I even can) is to combine them like but append the information horizontally.

For example appending two would look like the below;

  | AColumn  | BColumn  | CColumn  | Dcolumn
--+----------+----------+----------+---------
1 | Title    |          |          |
--+----------+----------+----------+---------
2 | Year     |          |          |
--+----------+----------+----------+---------
3 | Heading1 | Heading2 | Heading3 | Heading4 
--+----------+----------+----------+---------
4 | DATA1    | DATA2    | DATA3    | DATA4

The code I have already successfully deletes the title and year aside from the first file but it add the other files to the bottom.

Hopefully this is enough information but I'm around to add more if you need.

using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;


class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog
        {
            ShowNewFolderButton = false
        };

        string selectedFolder = @"C:\";
        folderBrowserDialog1.SelectedPath = selectedFolder;

        //If OK is pressed
        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
        {
            //Grab the folder that was chosen
            selectedFolder = folderBrowserDialog1.SelectedPath;
            //get all csv files
            string[] filepaths = Directory.GetFiles(selectedFolder, "*.csv");
            //create combined directory
            Directory.CreateDirectory(selectedFolder + "\\Combined\\");
            //define it as destination folder
            string destinationFolder = selectedFolder + "\\Combined\\";
            //define destination file name
            string destinationFile = "Combined.csv";

            StreamWriter fileDest = new StreamWriter(destinationFolder + destinationFile, true);
            for (int i = 0; i < filepaths.Length; i++)
            {
                try
                {
                    string file = filepaths[i];
                    string[] lines = File.ReadAllLines(file);
                    if (i > 0)
                    {
                        lines = lines.Skip(1).ToArray(); // Skip header row for all but first file
                    }

                    foreach (string line in lines)
                    {
                        fileDest.WriteLine(line);
                        Console.WriteLine(file);
                    }
                }

                catch (Exception)
                {
                    //nothing so far
                }
            }
            fileDest.Close();
            Console.Write("Press Enter to close");
            Console.ReadLine();
        }
    }
}

This is simple solution:

// first put data of all files in a list:
List<string[]> fileData = new List<string[]>();
for (int i = 0; i < filepaths.Length; i++)
{
    string file = filepaths[i];
    string[] lines = File.ReadAllLines(file);
    fileData.Add(lines);
}
//then combine them horizontally in another list
List<string> combined = new List<string>();
var maxCount = fileData.Max(x=>x.Length);
for (int i = 0; i < maxCount ; i++)
{
    combined.Add(string.Join(",", fileData.Select(x => x.Length > i ? x[i] : "")));
}

then you can write the combined data into destination file using File.WriteAllLines()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM