CSV文件中满足特定条件时如何将行拆分为新行?

时间:2019-05-29 07:34:14

标签: c# csv

我的csv文件中包含以下数据,当我使用c#识别“ 05/16/2019”文本时,我想将每一行拆分为一个新行。

当前在我的csv文件中,数据格式如下:

05/16/2019,PAPER,190516-TRE-5419,GbK,R0000001,1,05 / 16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1,05 / 16/2019,PAPER ,190516-TRE-5419,GSK,R0000001,1

我想像下面这样更改:

05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1
2019年5月16日,PAPER,190516-TRE-5419,GSK,R0000001,1
2019年5月16日,PAPER,190516-TRE-5419,GSK,R0000001,1

我是c#编程的新手,有人可以帮助我使用代码吗?

第一步:我正在上传我的csv文件
第二步:我正在尝试按照上述要求更改我的csv
第三步:将修改后的csv导出到新位置

List<string> csvfiles = new List<string>();
private void btnimport_Click(object sender, EventArgs e)
{
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.CheckFileExists = true;
        openFileDialog.AddExtension = true;
        openFileDialog.Multiselect = true;
        openFileDialog.Filter = "CSV files (*.csv)|*.csv";
        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            foreach (string fileName in openFileDialog.FileNames)
            {
                csvfiles.Add(fileName);
            }
        }
    }
public void csvedit()
    {
        String path = @"C:\Users\Sunil\Videos\original\GSK.csv";
        Regex r = new Regex(@",(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4})");   // looks for the comma just before the date
        var newStr = r.Replace(path, "\r\n");
    }
 private void btnexport_Click(object sender, EventArgs e)
    {
        csvedit();
        string installedPath = "C:\\Users\\Sunil\\Videos\\changed";

        //Check whether folder path is exist
        if (!System.IO.Directory.Exists(installedPath))
        {
            // If not create new folder
            System.IO.Directory.CreateDirectory(installedPath);
        }
        //Save pdf files in installedPath ??
        foreach (string sourceFileName in csvfiles)
        {
            string destinationFileName = System.IO.Path.Combine(installedPath, System.IO.Path.GetFileName(sourceFileName));
            System.IO.File.Copy(sourceFileName, destinationFileName);
            MessageBox.Show("File Exported Successfully");
        }
    }

1 个答案:

答案 0 :(得分:0)

假设当前CSV格式在代码中可以作为字符串使用,则可以使用正则表达式格式化所需的方式。试试这个:

Regex r = new Regex(@",(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4})");   // looks for the comma just before the date
var newStr = r.Replace(str, "\r\n");         // here 'str' is the input string which contains unformatted csv file content.

根据您的要求,您需要修改csvedit(),如下所示:

public void csvedit()
{
    string path = @"C:\Users\Sunil\Videos\original\GSK.csv";
    string csvContent = System.IO.File.ReadAllText(path);
    Regex r = new Regex(@"("",""(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4}))");  // looks for the 'double quotes - comma - double quotes' pattern just before the date
    var newStr = r.Replace(csvContent, "\n").Trim("\"".ToArray());
    System.IO.File.WriteAllText(path, newStr);    //this will overwrite the text present in existing file.
}