简体   繁体   English

c# 替换 CSV 中的标题文本

[英]c# Replace header text in CSV

I have a csv file as shown below我有一个 csv 文件,如下所示

在此处输入图片说明

I want to replace the text in the header.我想替换标题中的文本。 Aim is to replace _ underscores by a space.目的是用空格替换 _ 下划线。

Sample output样本输出

在此处输入图片说明

The Code I was trying was by using TextFieldParser我尝试的代码是使用TextFieldParser

private void CSV_Operation(string path)
{
    using (TextFieldParser parser = new TextFieldParser(path))
    {
        // set the parser variables
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");

        bool firstLine = true;

        while (!parser.EndOfData)
        {
            string[] fields = parser.ReadFields();
            if (firstLine && fields != null)
            {
                //Code to replace this in actual .csv file, below code does not save these changes in the original file
                for (int i = 0; i < fields.Count(); i++)
                {
                    fields[i] = fields[i].Replace('_', ' ');
                }
            }

            // get the column headers
            if (firstLine)
            {
                firstLine = false;
            }
        }
    }
}

I want to persist the changes done to the header text in the original file.我想保留对原始文件中的标题文本所做的更改。 Any help?有什么帮助吗?

If you want to change columns' heads (ie 1st line) only, while keeping csv body intact you can try如果您只想更改列的标题(即第一行),同时保持 csv 正文完整,您可以尝试

using System.IO;
using System.Linq;

...

private void CSV_Operation(string path) {
  var file = File
    .ReadLines(path)
    .SkipWhile(line => string.IsNullOrWhiteSpace(line)) // To be on the safe side
    .Select((line, index) => index == 0 // do we have header? 
       ? line.Replace('_', ' ') // replace '_' with ' '
       : line)                  // keep lines as they are 
    .ToList();                  // Materialization, since we write into the same file

  File.WriteAllLines(path, file);
}

A quick alternative could be:一个快速的替代方案可能是:

private void CSV_Operation(string path)
{
   File.WriteAllLines(path,  
                      File.ReadAllText(path).Replace('_', ' '),       
                      Encoding.UTF8);
}

You could do something like this你可以做这样的事情

//read all the lines but skip the first
var lines = File.ReadLines(Server.MapPath("/test.csv")).Skip(1).ToList();

//create a new header if you want more than just remove the _
string newHeader = "ID;Name;Address;Contact";

//merge both
string newCsv = string.Format("{0}\r\n{1}", newHeader, string.Join("\r\n", lines));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM