Writing data into CSV file in C#

后端 未结 15 1203
清酒与你
清酒与你 2020-11-22 17:15

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.         


        
相关标签:
15条回答
  • 2020-11-22 17:37

    Instead of calling every time AppendAllText() you could think about opening the file once and then write the whole content once:

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:40
    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();
    
    0 讨论(0)
  • 2020-11-22 17:41

    Writing csv files by hand can be difficult because your data might contain commas and newlines. I suggest you use an existing library instead.

    This question mentions a few options.

    Are there any CSV readers/writer libraries in C#?

    0 讨论(0)
  • 2020-11-22 17:46

    Instead of reinventing the wheel a library could be used. CsvHelper is great for creating and reading csv files. It's read and write operations are stream based and therefore also support operations with a big amount of data.


    You can write your csv like the following.

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

    As the library is using reflection it will take any type and parse it directly.

    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,true

    value2,false


    If you want to read more about the librarys configurations and possibilities you can do so here.

    0 讨论(0)
  • 2020-11-22 17:50

    You might just have to add a line feed "\n\r".

    0 讨论(0)
  • 2020-11-22 17:51
    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 WriteFields(this StreamWriter writer, params string[] fields) => WriteFields(writer, (IEnumerable<string>)fields);
    }
    

    This should allow you to write a csv file quite simply. Usage:

    StreamWriter writer = new StreamWriter("myfile.csv");
    writer.WriteCSVLine(new[]{"A", "B"});
    
    0 讨论(0)
提交回复
热议问题