追加相同的CSV在一起,同时移除页眉 [英] Appending identical CSVs together while removing headers

查看:141
本文介绍了追加相同的CSV在一起,同时移除页眉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想追加6 CSV格式具有相同的布局和头在一起。

I am wanting to append 6 CSVs that have identical layouts and headers together.

我已经能够通过每个6中的CSV加载到自己单独的数据表和删除每个DataTable的第一行来实现。最后我用ImportRow方法追加在一起。

I've been able to accomplish this by loading each of the 6 csvs into their own seperate data tables and removing the first row of each datatable. Finally I've appended them together using the ImportRow method.

DataTable table1 = csvToDataTable(@"C:\Program Files\Normalization\Scan1.csv");
DataTable table2 = csvToDataTable(@"C:\Program Files\Normalization\Scan2.csv");
DataTable table3 = csvToDataTable(@"C:\Program Files\Normalization\Scan3.csv");
DataTable table4 = csvToDataTable(@"C:\Program Files\Normalization\Scan4.csv");
DataTable table5 = csvToDataTable(@"C:\Program Files\Normalization\Scan5.csv");
DataTable table6 = csvToDataTable(@"C:\Program Files\Normalization\Scan6.csv");

        foreach (DataRow dr in table2.Rows)
        {
            table1.ImportRow(dr);
        }
        foreach (DataRow dr in table3.Rows)
        {
            table1.ImportRow(dr);
        }
        foreach (DataRow dr in table4.Rows)
        {
            table1.ImportRow(dr);
        }
        foreach (DataRow dr in table5.Rows)
        {
            table1.ImportRow(dr);
        }
        foreach (DataRow dr in table6.Rows)
        {
            table1.ImportRow(dr);
        }

        CreateCSVFile(table1, @"C:\Program Files\Normalization\RackMap.csv");

我觉得这是笨重的,不是很可扩展性,但​​我有麻烦处理头,当我试图在CSV级追加。有什么建议?

I feel this is clunky and not very scalable but I had trouble dealing with the headers when I tried to append at the CSV level. Any suggestions?

TIA

推荐答案

获取匹配的面具所有文件的DirectoryInfo的 *。csv格式

Get a DirectoryInfo of all files matching the mask *.csv

for循环迭代的结果创建。

Create a for loop to iterate the results.

每个导入文件时丢弃的第一行。

Drop the first row when importing each file.

编辑:

如果你只是想结合文件,而不是导入到一个数据表,你可以把它们当作文本文件。将它们连接起来,每一次下探标题行。下面是一个例子:

If you just want to combine the files, rather than import into a data table, you could treat them as text files. Concatenate them, dropping the header line each time. Here is an example:

string myPath = @"K:\csv";

DirectoryInfo csvDirectory = new DirectoryInfo(myPath);
FileInfo[] csvFiles = csvDirectory.GetFiles("*.csv");
StringBuilder sb = new StringBuilder();
foreach (FileInfo csvFile in csvFiles)
    using (StreamReader sr = new StreamReader(csvFile.OpenRead()))
    {
        sr.ReadLine(); // Discard header line
        while (!sr.EndOfStream)
            sb.AppendLine(sr.ReadLine());
    }
File.AppendAllText(Path.Combine(myPath, "output.csv"), sb.ToString());

这篇关于追加相同的CSV在一起,同时移除页眉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆