读取CSV文件,然后将其作为CSV文件重新导出到Excel

时间:2016-08-09 13:25:37

标签: c#

我已经阅读了csv文件,现在我只想将其重新导出回excel以查看对该文件所做的更改。我也尝试使用Excel作为一个广泛的自动化API,但不知道如何执行此过程。

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

        var lines = File.ReadAllLines(fileName);
        for (var i = 0; i < lines.Length; i++)
        {
            // Skip the line with column names
            if (i == 0)
            {
                continue;
            }

            // Splitting by space. I assume this is the pattern
            var replace = lines[i].Replace(' ', ',');

            results.Add(replace);
        }

        return results;
    }

1 个答案:

答案 0 :(得分:1)

您是否正在寻找一些 Linq ,这样的实现

   var target = File
     .ReadLines(fileName)
     .Skip(1) // Skip the line with column names
     .Select(line => line.Replace(' ', ',')); // ... I assume this is the pattern

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

   // In case you want to write to fileName back, materialize:
   // File.WriteAllLines(fileName, target.ToList());