Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# csv修改文件_C#_Csv - Fatal编程技术网

C# csv修改文件

C# csv修改文件,c#,csv,C#,Csv,关于我们公司正在使用的整合应用程序,我有点为难。我们从进度数据库创建了一个csv文件。这个csv文件有14列,没有标题 CSV文件包含付款(约17.3万行)。除列金额(最后一列)外,这些行中的大多数都相同 例如: 2014;MONTH;;SC;10110;;;;;;;;EUR;-6500000 2014;01;;SC;10110;;;;;;;;EUR;-1010665 2014;01;;LLC;11110;;;;;;;;EUR;-6567000 2014;01;;SC;10110;;;;;;;;

关于我们公司正在使用的整合应用程序,我有点为难。我们从进度数据库创建了一个csv文件。这个csv文件有14列,没有标题

CSV文件包含付款(约17.3万行)。除列金额(最后一列)外,这些行中的大多数都相同

例如:

2014;MONTH;;SC;10110;;;;;;;;EUR;-6500000
2014;01;;SC;10110;;;;;;;;EUR;-1010665
2014;01;;LLC;11110;;;;;;;;EUR;-6567000
2014;01;;SC;10110;;;;;;;;EUR;-1110665
2014;01;;LLC;11110;;;;;;;;EUR;65670.00
2014;01;;SC;10110;;;;;;;;EUR;-11146.65
(约174000行)

正如您所看到的,除了“金额”列之外,这些行中的某些行是相同的。我需要的是对所有行进行排序,将金额相加并保存一个唯一的行,而不是1100行不同的金额

我的编码技能让我无法在一定的时间内完成工作,也许你们中的一位可以推动我朝着正确的方向解决这个问题

示例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = File.ReadAllText(@"c:\temp\test.txt");
            string inputLine = "";
            StringReader reader = new StringReader(input);
            List<List<string>> data = new List<List<string>>();
            while ((inputLine = reader.ReadLine()) != null)
            {
                if (inputLine.Trim().Length > 0)
                {
                    string[] inputArray = inputLine.Split(new char[] { ';' });
                    data.Add(inputArray.ToList());
                }
            }
            //sort data by every column
            for (int sortCol = data[0].Count() - 1; sortCol >= 0; sortCol--)
            {
                data.OrderBy(x => x[sortCol]); 
            }
            //delete duplicate rows
            for (int rowCount = data.Count - 1; rowCount >= 1; rowCount--)
            {
                Boolean match = true;
                for (int colCount = 0; colCount < data[rowCount].Count - 2; colCount++)
                {
                    if(data[rowCount][colCount] != data[rowCount - 1][colCount])
                    {
                        match = false;
                        break;
                    }
                }
                if (match == true)
                {
                    decimal previousValue = decimal.Parse(data[rowCount - 1][data[rowCount].Count - 1]);
                    decimal currentValue = decimal.Parse(data[rowCount][data[rowCount].Count - 1]);
                    string newStrValue = (previousValue + currentValue).ToString();
                    data[rowCount - 1][data[rowCount].Count - 1] = newStrValue;
                    data.RemoveAt(rowCount);
                }
            }

            string output = string.Join("\r\n",data.AsEnumerable()
                .Select(x => string.Join(";",x.Select(y => y).ToArray())).ToArray());
            File.WriteAllText(@"c:\temp\test1.txt",output);
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.IO;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串输入=File.ReadAllText(@“c:\temp\test.txt”);
字符串inputLine=“”;
StringReader=新的StringReader(输入);
列表数据=新列表();
而((inputLine=reader.ReadLine())!=null)
{
如果(inputLine.Trim().Length>0)
{
字符串[]inputArray=inputLine.Split(新字符[]{';'});
Add(inputArray.ToList());
}
}
//按每列对数据进行排序
对于(int-sortCol=data[0]。计数()-1;sortCol>=0;sortCol--)
{
OrderBy(x=>x[sortCol]);
}
//删除重复行
对于(int rowCount=data.Count-1;rowCount>=1;rowCount--)
{
布尔匹配=真;
对于(int colCount=0;colCountstring.Join(“;”,x.Select(y=>y.ToArray()).ToArray());
writealText(@“c:\temp\test1.txt”,输出);
}
}
}

逐行读取CSV文件,并构建一个内存字典,在其中保存总计(以及所需的其他信息)。由于大多数行属于同一个键,因此可能不会导致内存不足问题。然后,根据字典中的信息生成一个新的CSV。

当我解释您的问题时,您的问题和您要求的解决方案是如何以

@"2014;MONTH;;SC;10110;;;;;;;;EUR;-6500000
2014;01;;SC;10110;;;;;;;;EUR;-1010665
2014;01;;LLC;11110;;;;;;;;EUR;-6567000
2014;01;;SC;10110;;;;;;;;EUR;-1110665
2014;01;;LLC;11110;;;;;;;;EUR;65670.00
2014;01;;SC;10110;;;;;;;;EUR;-11146.65"
得到最后一列,然后求和?如果是这样的话,用这样的东西做起来其实很容易

public static void Main()
    {
        string input = @"2014;MONTH;;SC;10110;;;;;;;;EUR;-6500000
2014;01;;SC;10110;;;;;;;;EUR;-1010665
2014;01;;LLC;11110;;;;;;;;EUR;-6567000
2014;01;;SC;10110;;;;;;;;EUR;-1110665
2014;01;;LLC;11110;;;;;;;;EUR;65670.00
2014;01;;SC;10110;;;;;;;;EUR;-11146.65";

        var rows = input.Split('\n');

        decimal totalValue = 0m;

        foreach(var row in rows)
        {           
            var transaction = row.Substring(row.LastIndexOf(';') +1);

            decimal val = 0m;

            if(decimal.TryParse(transaction, out val))
                totalValue += val;
        }

        Console.WriteLine(totalValue);
    }

但也许我误解了你的要求?

很抱歉这么晚才回复我的帖子,但这是我最后的解决办法

替换所有“字符并将输出写入流写入器。(从25mb到15mb文件。)。然后将我的CSV文件复制到SQL server,以便我可以批量插入。插入后,我只需查询表并将结果集读/写到新文件。我的新文件只有+/-700KB

Filldata()方法在我的应用程序中填充datagridview,以便您可以查看结果,而不是在excel中打开文件

我是C#新手,目前正在编写一个新的解决方案,直接或在内存中查询csv文件,并将其写回新文件

方法1:

                string line;

                StreamWriter sw = new StreamWriter(insertFile);

                using (StreamReader sr = new StreamReader(sourcePath))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        sw.WriteLine(line.Replace("\"", ""));
                    }

                    sr.Close();
                    sw.Close();
                    sr.Dispose();
                    sw.Dispose();

                    File.Copy(insertFile, @"\\SQLSERVER\C$\insert.csv");

                }
方法2:

var destinationFile = @"c:\insert.csv";

                var querieImportCSV = "BULK INSERT dbo.TABLE FROM '" + destinationFile + "' WITH ( FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', FIRSTROW = 1)";
                var truncate = @"TRUNCATE TABLE dbo.TABLE";

              string queryResult =
      @"SELECT [Year]
              ,[Month]
              ,[Week]
              ,[Entity]
              ,[Account]
              ,[C11]
              ,[C12]
              ,[C21]
              ,[C22]
              ,[C3]
              ,[C4]
              ,[CTP]
              ,[VALUTA]
              ,SUM(AMOUNT) as AMOUNT
              ,[CURRENCY_ORIG]
              ,[AMOUNTEXCH]
              ,[AGENTCODE]
            FROM dbo.TABLE
            GROUP BY YEAR, MONTH, WEEK, Entity, Account, C11, C12, C21, C22, C3, C4, CTP, VALUTA, CURRENCY_ORIG, AMOUNTEXCH, AGENTCODE
            ORDER BY Account";

                var conn = new SqlConnection(connectionString);

                conn.Open();
                SqlCommand commandTruncate = new SqlCommand(truncate, conn);
                commandTruncate.ExecuteNonQuery();

                SqlCommand commandInsert = new SqlCommand(querieImportCSV, conn);
                SqlDataReader readerInsert = commandInsert.ExecuteReader();
                readerInsert.Close();

                FillData();

                SqlCommand commandResult = new SqlCommand(queryResult, conn);
                SqlDataReader readerResult = commandResult.ExecuteReader();

                StringBuilder sb = new StringBuilder(); 

                while (readerResult.Read())
                {
                        sb.Append(readerResult["Year"] + ";" + readerResult["Month"] + ";" + readerResult["Week"] + ";" + readerResult["Entity"] + ";" + readerResult["Account"] + ";" +
                        readerResult["C11"] + ";" + readerResult["C12"] + ";" + readerResult["C21"] + ";" + readerResult["C22"] + ";" + readerResult["C3"] + ";" + readerResult["C4"] + ";" +
                        readerResult["CTP"] + ";" + readerResult["Valuta"] + ";" + readerResult["Amount"] + ";" + readerResult["CURRENCY_ORIG"] + ";" + readerResult["AMOUNTEXCH"] + ";" + readerResult["AGENTCODE"]);
                }
                sb.Replace("\"","");

                StreamWriter sw = new StreamWriter(homedrive);
                sw.WriteLine(sb);

                readerResult.Close();
                conn.Close();
                sw.Close();
                sw.Dispose();

到目前为止,您所尝试的是输入文件相当小,以至于可以完全读入内存?如果您从数据库创建CSV文件,这意味着您可以直接使用数据库?在数据库级别这样做会容易得多。为什么不在Excel中打开它?为什么我的用户应该在Excel中进行而不是仅在Excel中进行自动地为他们。