用c#编写数据到CSV文件

我试图用c#语言一行一行地写入csv文件。这是我的函数

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文件中的所有行?

893159 次浏览

你可以使用AppendAllText代替:

File.AppendAllText(filePath, csv);

正如WriteAllText的文档所说:

如果目标文件已经存在,那么它将被覆盖

此外,请注意您当前的代码没有使用适当的新行,例如在记事本中,您将看到它都是一个长行。将代码更改为这样,以获得正确的新行:

string csv = string.Format("{0},{1}{2}", first, image, Environment.NewLine);

更新

回到我naïve的日子里,我建议手动做这个(这是一个简单问题的简单解决方案),然而,由于这变得越来越流行,我建议使用库CsvHelper,它做所有的安全检查,等等。

CSV比问题/答案所暗示的要复杂得多。

原来的答案

因为你已经有了一个循环,考虑这样做:

//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());

或者类似的东西。 我的理由是:你不需要为每一项写入文件,你只需要打开流一次,然后写入它

你可以替换

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

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

如果您希望将CSV的以前版本保存在同一文件中

C # 6

如果您正在使用c# 6.0,那么您可以执行以下操作

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

编辑

这里有一个链接来回答一个问题,解释了Environment.NewLine的作用。

我强烈建议你走更乏味的路线。尤其是当你的文件很大的时候。

using(var w = new StreamWriter(path))
{
for( /* your loop */)
{
var first = yourFnToGetFirst();
var second = yourFnToGetSecond();
var line = string.Format("{0},{1}", first, second);
w.WriteLine(line);
w.Flush();
}
}

File.AppendAllText()打开一个新文件,写入内容,然后关闭文件。与将数据写入开放流相比,打开文件是一个耗费大量资源的操作。在循环中打开/关闭文件会导致性能下降。

Johan建议的方法解决了这个问题,方法是将所有输出存储在内存中,然后只写入一次。然而(在大文件的情况下)你的程序将消耗大量的RAM,甚至崩溃与OutOfMemoryException

我的解决方案的另一个优点是,您可以通过保存输入数据中的当前位置来实现暂停/恢复。

乌利希期刊指南。把使用放在正确的地方

而不是每次调用AppendAllText(),你可以考虑打开文件一次,然后把整个内容写一次:

var file = @"C:\myOutput.csv";


using (var stream = File.CreateText(file))
{
for (int i = 0; i < reader.Count(); i++)
{
string first = reader[i].ToString();
string second = image.ToString();
string csvRow = string.Format("{0},{1}", first, second);


stream.WriteLine(csvRow);
}
}

我使用双解析解决方案,因为它非常容易维护

// Prepare the values
var allLines = (from trade in proposedTrades
select new object[]
{
trade.TradeType.ToString(),
trade.AccountReference,
trade.SecurityCodeType.ToString(),
trade.SecurityCode,
trade.ClientReference,
trade.TradeCurrency,
trade.AmountDenomination.ToString(),
trade.Amount,
trade.Units,
trade.Percentage,
trade.SettlementCurrency,
trade.FOP,
trade.ClientSettlementAccount,
string.Format("\"{0}\"", trade.Notes),
}).ToList();


// Build the file content
var csv = new StringBuilder();
allLines.ForEach(line =>
{
csv.AppendLine(string.Join(",", line));
});


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

你可能只需要添加换行"\n\r"

手动编写csv文件可能很困难,因为数据可能包含逗号和换行符。我建议您使用现有的库。

这个问题提到了几个选项。

c#中有CSV读取器/写入器库吗?< / >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;


public partial class CS : System.Web.UI.Page
{
protected void ExportCSV(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);


//Build the CSV file data as a Comma separated string.
string csv = string.Empty;


foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}


//Add new line.
csv += "\r\n";


foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}


//Add new line.
csv += "\r\n";
}


//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
}
}
}
}
}

处理逗号

对于在使用string.Format(...)时处理值内部的逗号,以下方法对我有用:

var newLine = string.Format("\"{0}\",\"{1}\",\"{2}\"",
first,
second,
third
);
csv.AppendLine(newLine);

所以把它和约翰的答案结合起来,看起来是这样的:

//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());

返回CSV文件

如果你只是想返回文件,而不是把它写到一个位置,这是我如何完成它的一个例子:

从存储过程

public FileContentResults DownloadCSV()
{
// I have a stored procedure that queries the information I need
SqlConnection thisConnection = new SqlConnection("Data Source=sv12sql;User ID=UI_Readonly;Password=SuperSecure;Initial Catalog=DB_Name;Integrated Security=false");
SqlCommand queryCommand = new SqlCommand("spc_GetInfoINeed", thisConnection);
queryCommand.CommandType = CommandType.StoredProcedure;


StringBuilder sbRtn = new StringBuilder();


// If you want headers for your file
var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
"Name",
"Address",
"Phone Number"
);
sbRtn.AppendLine(header);


// Open Database Connection
thisConnection.Open();
using (SqlDataReader rdr = queryCommand.ExecuteReader())
{
while (rdr.Read())
{
// rdr["COLUMN NAME"].ToString();
var queryResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
rdr["Name"].ToString(),
rdr["Address"}.ToString(),
rdr["Phone Number"].ToString()
);
sbRtn.AppendLine(queryResults);
}
}
thisConnection.Close();


return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

从列表中

/* To help illustrate */
public static List<Person> list = new List<Person>();


/* To help illustrate */
public class Person
{
public string name;
public string address;
public string phoneNumber;
}


/* The important part */
public FileContentResults DownloadCSV()
{
StringBuilder sbRtn = new StringBuilder();


// If you want headers for your file
var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
"Name",
"Address",
"Phone Number"
);
sbRtn.AppendLine(header);


foreach (var item in list)
{
var listResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
item.name,
item.address,
item.phoneNumber
);
sbRtn.AppendLine(listResults);
}
}


return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

希望这对你们有帮助。

可以使用库而不是重新发明轮子。CsvHelper非常适合创建和读取csv文件。它的读写操作是基于流的,因此也支持有大量数据的操作。


您可以像下面这样编写csv文件。

using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv"))
{
var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
writer.Configuration.Delimiter = ",";


foreach (var item in list)
{
writer.WriteField( "a" );
writer.WriteField( 2 );
writer.WriteField( true );
writer.NextRecord();
}
}

由于库正在使用反射,它将接受任何类型并直接解析它。

public class CsvRow
{
public string Column1 { get; set; }
public bool Column2 { get; set; }


public CsvRow(string column1, bool column2)
{
Column1 = column1;
Column2 = column2;
}
}


IEnumerable<CsvRow> rows = new [] {
new CsvRow("value1", true),
new CsvRow("value2", false)
};
using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv")
{
var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
writer.Configuration.Delimiter = ",";
writer.WriteRecords(rows);
}

value1,真

value2,假


如果你想阅读更多关于库的配置和可能性,你可以这样做在这里

下面是另一个开源库,可以轻松创建CSV文件Cinchoo ETL

List<dynamic> objs = new List<dynamic>();


dynamic rec1 = new ExpandoObject();
rec1.Id = 10;
rec1.Name = @"Mark";
rec1.JoinedDate = new DateTime(2001, 2, 2);
rec1.IsActive = true;
rec1.Salary = new ChoCurrency(100000);
objs.Add(rec1);


dynamic rec2 = new ExpandoObject();
rec2.Id = 200;
rec2.Name = "Tom";
rec2.JoinedDate = new DateTime(1990, 10, 23);
rec2.IsActive = false;
rec2.Salary = new ChoCurrency(150000);
objs.Add(rec2);


using (var parser = new ChoCSVWriter("emp.csv").WithFirstLineHeader())
{
parser.Write(objs);
}

有关更多信息,请阅读有关用法的CodeProject上文章。

这是一个使用c#创建csv文件的简单教程,您将能够编辑和扩展以适应自己的需要。

首先,您需要创建一个新的Visual Studio c#控制台应用程序,需要遵循以下步骤来完成此操作。

示例代码将在您指定的位置创建一个名为MyTest.csv的csv文件。文件的内容应该是3个命名列,前3行是文本。

https://tidbytez.com/2018/02/06/how-to-create-a-csv-file-with-c/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace CreateCsv
{
class Program
{
static void Main()
{
// Set the path and filename variable "path", filename being MyTest.csv in this example.
// Change SomeGuy for your username.
string path = @"C:\Users\SomeGuy\Desktop\MyTest.csv";


// Set the variable "delimiter" to ", ".
string delimiter = ", ";


// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Column 1 Name" + delimiter + "Column 2 Name" + delimiter + "Column 3 Name" + delimiter + Environment.NewLine;
File.WriteAllText(path, createText);
}


// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is text for Column 1" + delimiter + "This is text for Column 2" + delimiter + "This is text for Column 3" + delimiter + Environment.NewLine;
File.AppendAllText(path, appendText);


// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
}

消除覆盖问题的一个简单方法是使用File.AppendText在文件末尾追加一行as

void Main()
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText("file.txt"))
{
string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}\n", first, second);
sw.WriteLine(csv);
}
}
enter code here

string string_value= string. empty;

        for (int i = 0; i < ur_grid.Rows.Count; i++)
{
for (int j = 0; j < ur_grid.Rows[i].Cells.Count; j++)
{
if (!string.IsNullOrEmpty(ur_grid.Rows[i].Cells[j].Text.ToString()))
{
if (j > 0)
string_value= string_value+ "," + ur_grid.Rows[i].Cells[j].Text.ToString();
else
{
if (string.IsNullOrEmpty(string_value))
string_value= ur_grid.Rows[i].Cells[j].Text.ToString();
else
string_value= string_value+ Environment.NewLine + ur_grid.Rows[i].Cells[j].Text.ToString();
}
}
}
}




string where_to_save_file = @"d:\location\Files\sample.csv";
File.WriteAllText(where_to_save_file, string_value);


string server_path = "/site/Files/sample.csv";
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(server_path));
Response.WriteFile(server_path);
Response.End();
public static class Extensions
{
public static void WriteCSVLine(this StreamWriter writer, IEnumerable<string> fields)
{
const string q = @"""";
writer.WriteLine(string.Join(",",
fields.Select(
v => (v.Contains(',') || v.Contains('"') || v.Contains('\n') || v.Contains('\r')) ? $"{q}{v.Replace(q, q + q)}{q}" : v
)));
}


public static void WriteCSVLine(this StreamWriter writer, params string[] fields) => WriteCSVLine(writer, (IEnumerable<string>)fields);
}

这将允许您非常简单地编写csv文件。用法:

StreamWriter writer = new ("myfile.csv");
writer.WriteCSVLine("A", "B"); // A,B