簡體   English   中英

如何將更改應用於CSV文件中的特定列?

[英]How to apply changes to a specific column in the CSV file?

在我的CSV文件中,我有一列包含一個字符串和一個日期時間類型。 這是我的CSV文件中包含此數據的第5列(TUI 01/01/01)。 我對空格進行了一些更改,以逗號分隔該值在兩個不同的列中(TUI,01/01/01)。 但是,這些更改會影響其他列數據,這些列數據的值之間有一個空格。 我只想將這些更改應用於影響第五欄。

任何建議都會令人贊賞。

 static void Main(string[] args)
    {
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "InventoryReport 02_08_2016.csv");
        var fileContents = ReadFile(filePath);
        foreach (var line in fileContents)
        {
            Console.WriteLine(line);
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }

    public static IList<string> ReadFile(string fileName)
    {
        var results = new List<string>();

        var target = File
 .ReadAllLines(fileName)
 .Skip(1) // Skip the line with column names
 .Select(line => line.Replace(' ', ',')); // ... splitting  pattern

        // Writing back to some other file
        File.WriteAllLines(fileName, target);

        return results;
    }
}

好吧,您顯然將替換替換應用於整個文件,這就是為什么它影響所有列的原因,請嘗試另一種方法:
循環每行
-在每個循環中使用逗號分割元素

var lineElements = line.split(',');

-然后將其專門應用於第5列:

var fifthElement = lineElements[4].Replace(' ', ',');

-將僅在第五元素上應用效果
-組合起來,像以前一樣整條生產線

您當前的方式會影響整行( .Select(line => line.Replace(' ', ',')) ),而不僅僅是行的第5個字段。 這是另一種方式。

選項1

    public Form1()
    {
        InitializeComponent();
        ReWriteFile(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata.csv");//call the method
    }

    public void ReWriteFile(string fileName)
    {
        using (StreamWriter sw = new StreamWriter(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata_new.csv"))
        {
            string currentLine = string.Empty;
            using (StreamReader sr = new StreamReader(fileName))//
            {
                while ((currentLine = sr.ReadLine()) != null)//while there are lines to read
                {
                    string[] fielded = currentLine.Split(',');//split your fields into an array
                    fielded[4] = fielded[4].Replace(" ", ",");//replace the space in position 4(field 5) of your array
                    sw.WriteLine(string.Join(",", fielded));//write the line in the new file
                }
            }
        }

    }

我的起始數據是這樣的( 列數不匹配,但是對於這個問題,它並沒有阻止任何事情發生 ):

col1,col2,col3,col4,col5,col6
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data

經過此方法后,結果變為:

col1,col2,col3,col4,col5,col6
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data

在這里閱讀了您的問題后, 如何在csv文件中顯示列名,我意識到您必須出於充分的理由而跳過第一行,因此我更新了代碼以同時解決您的問題。

此選項按原樣寫入標頭記錄

    /// <summary>
    /// In this method I use the lineCounter as my position tracker to know which line I'm readin at the time
    /// </summary>
    /// <param name="fileName"></param>
    public void ReWriteFileDontAffectFirstRow(string fileName)
    {
        int lineCounter = 0;//lets make our own position tracker
        using (StreamWriter sw = new StreamWriter(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata_new2.csv"))
        {
            string currentLine = string.Empty;
            using (StreamReader sr = new StreamReader(fileName))
            {
                while ((currentLine = sr.ReadLine()) != null)//while there are lines to read
                {
                    if (lineCounter != 0)
                    {
                        //If it's not the first line
                        string[] fielded = currentLine.Split(',');//split your fields into an array
                        fielded[4] = fielded[4].Replace(" ", ",");//replace the space in position 4(field 5) of your array
                        sw.WriteLine(string.Join(",", fielded));//write the line in the new file
                    }
                    else
                    {
                        //If it's the first line
                        sw.WriteLine(currentLine);//Write the line as-is
                    }
                    lineCounter++;
                }
            }
        }
    }

原始數據是這樣的( 列數不匹配,但是對於此問題,它並不能阻止任何事情正常運行

col 1,col 2,col 3,col 4,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data,col 6 data

通過該方法后的數據

col 1,col 2,col 3,col 4,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data,col 6 data

此選項將字段添加到標題記錄

    public void ReWriteFileAdjustHeaderRecordToo(string fileName)
    {
        int lineCounter = 0;//lets make our own position tracker
        using (StreamWriter sw = new StreamWriter(@"M:\StackOverflowQuestionsAndAnswers\38873875\38873875\testdata_new3.csv"))
        {
            string currentLine = string.Empty;
            using (StreamReader sr = new StreamReader(fileName))
            {
                while ((currentLine = sr.ReadLine()) != null)//while there are lines to read
                {
                    List<string> fielded = new List<string>(currentLine.Split(','));//splits your fields into a list of fields. This is no longer a string[]. Its a list so we can "inject" the new column in the header record.
                    if (lineCounter != 0)
                    {
                        //If it's not the first line
                        fielded[4] = fielded[4].Replace(" ", ",");//replace the space in position 4(field 5) of your array
                        sw.WriteLine(string.Join(",", fielded));//write the line in the new file
                    }
                    else
                    {
                        //If it's the first line
                        fielded.Insert(4, "new inserted col");//inject the new column into the list
                        sw.WriteLine(string.Join(",", fielded));//write the line in the new file
                    }
                    lineCounter++;
                }
            }
        }
    }

起始數據( 此數據具有正確的起始列數

col 1,col 2,col 3,col 4,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI 01/01/01,col 5 data

方法后的數據

col 1,col 2,col 3,col 4,new inserted col,col 5,col 6
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data
col 1 data,col 2 data,col 3 data,col 4 data,TUI,01/01/01,col 5 data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM