将数据写入CSV文件 [英] Writing data into CSV file

查看:192
本文介绍了将数据写入CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用C#语言逐行写入 csv 文件。这是我的函数

I am trying to write into a csv file row by row using C# language. Here is my function

string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}\n", first, second);
File.WriteAllText(filePath, csv);

整个函数在一个循环内运行,每一行都应该写入 csv 文件。在我的情况下,下一行覆盖现有的行,最后我得到的单个记录在csv文件是最后一个。如何写入 csv 文件中的所有行。

The whole function runs inside a loop, and every row should be written to the csv file. In my case next row overwrites the existing row and in the end I am getting only single record in the csv file which is last one. How can I write all the rows in the csv file.

推荐答案

由于你已经有一个循环,请考虑这样做:

As you already have a loop, consider doing it like this:

//before your loop
    var csv = new StringBuilder();

//in your loop
    var first = reader[0].ToString();
    var second = image.ToString();
    //Suggestion made by KyleMit
    var newLine = string.Format("{0},{1}", first, second);
    csv.AppendLine(newLine);  

//after your loop
    File.WriteAllText(filePath, csv.ToString());

或者这样的效果。
我的推理是:你不需要写入每个项目的文件,你只会打开一次流,然后写入。

Or something to this effect. My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.

您可以替换

File.WriteAllText(filePath, csv.ToString());

File.AppendAllText(filePath, csv.ToString());

如果要将csv的先前版本保留在同一文件中

if you want to keep previous versions of csv in the same file

C#6

如果您使用的是c#6.0,则可以执行以下操作:

If you are using c# 6.0 then you can do the following

var newLine = $"{first},{second}"

EDIT

这里是到解释 Environment.NewLine 做什么的问题

这篇关于将数据写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆