c# - 水平合并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()
推荐阅读
- java - 如何删除 mac 中与 rJava 相关的错误消息
- python - 通过字典解析字符串
- php - Laravel LengthAwarePaginator where 查询
- haskell - 将负责从各种函子中提取值的代码放在哪里
- python - 用于清理文档的深度学习模型
- c# - 如果我设置数据上下文,则可见性属性不起作用,反之亦然
- javascript - 在模态中从选择中设置 PHP 变量
- php - Sonata Admin - 更改过滤器值(关系字段)
- eclipse - 如何在 Eclipse Luna 中将现有文件的编码转换为 UTF-8
- python - 如果我必须添加一个以 3 为间隔的值的系列,python 中的代码将是什么