水平组合csv文件



我有一个小项目想用C#完成,我不是专家,但我还没有找到任何其他解决方案,所以我可能不知道该找什么。

我有几个csv文件是这样设置的;

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

我想做的(我不确定我是否能(是将它们组合起来,就像水平地附加信息一样。

例如,添加两个如下所示;

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

我已经成功地删除了第一个文件中的标题和年份,但它将其他文件添加到了底部。

希望这是足够的信息,但如果你需要,我会补充更多。

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();
}
}
}

这是一个简单的解决方案:

// 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] : "")));
}

然后可以使用File.WriteAllLines()将组合数据写入目标文件

最新更新