Writing a CSV file in .net

前端 未结 11 1359
生来不讨喜
生来不讨喜 2020-11-27 18:59

I have a requirement to export a dataset as a CSV file.

I have spent a while searching for a set of rules to go by and realised there are quite a few rules and exce

相关标签:
11条回答
  • 2020-11-27 19:20

    I know you said you found your answer, but I just wanted to give a vote for the LINQtoCSV library you mentioned. I've used it in a couple projects and it works really well for keeping your business code clean and not concerned with details / peculiarities of the file format.

    Maybe in your specific case it is not too difficult to write the exporter, but the nice thing about this library is that it is bidirectional. If you find yourself having to consume the CSV down the road it's not much extra code, and/or it gives you a consistent library to use on future projects.

    0 讨论(0)
  • 2020-11-27 19:23

    Another rule to add to the others: Use the commas as field separators rather than as field terminators. The reason for this is that a trailing comma at the end of a line could be ambiguous: Does it have no significance or does it signify a NULL value following it?

    0 讨论(0)
  • 2020-11-27 19:26

    For the specifications, see http://en.wikipedia.org/wiki/Comma-separated_values

    0 讨论(0)
  • 2020-11-27 19:27

    CsvHelper (a library I maintain) also available via NuGet.

    CsvHelper can automatically write your class objects to a file for you.

    var myObj = new MyCustomClass
    {
        Prop1 = "one",
        Prop2 = 2
    };
    var streamWriter = // Create a writer to somewhere...
    var csvWriter = new CsvWriter( streamWriter );
    
    // You can write a single record.
    csvWriter.WriteRecord( myObj );
    
    // You can also write a collection of records.
    var myRecords = new List<MyCustomClass>{ myObj };
    csvWriter.WriteRecords( myRecords );
    
    0 讨论(0)
  • 2020-11-27 19:30

    You can use ODBC to read and write CSV files (via OdbcConnection and a suitable connection string). This should be reasonably good for generating CSV files, and will handle things like quoting for you; however I have run into some issues when using it to read CSV files generated by other programs.

    0 讨论(0)
  • 2020-11-27 19:30

    I found this important link which is quite neat. Haven't tried it yet, will let you know how it goes!

    http://www.codeproject.com/KB/linq/LINQtoCSV.aspx

    Looking more closely, this implementation essentially only uses basic rules too:

    special chars = \n \" and the separator char.

    if found special characters, then surround with quotes. Replace quote with double quote.

    Essentially the rules Chris mentioned. I think the easiest way to do this is to create my helper method based on the simple rules and revise on a user-needs basis.

    0 讨论(0)
提交回复
热议问题