Writing data into CSV file in C#

后端 未结 15 1212
清酒与你
清酒与你 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:54
    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();
                        }
                    }
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:55

    This is a simple tutorial on creating csv files using C# that you will be able to edit and expand on to fit your own needs.

    First you’ll need to create a new Visual Studio C# console application, there are steps to follow to do this.

    The example code will create a csv file called MyTest.csv in the location you specify. The contents of the file should be 3 named columns with text in the first 3 rows.

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

    Simply use AppendAllText instead:

    File.AppendAllText(filePath, csv);
    

    The only downside of the AppendAllText is that it will throw error when file does not exist, so this must be checked

    Sorry, blonde moment before reading the documentation. Anyway, the WriteAllText method overwrites anything that was previously written in the file, if the file exists.

    Note that your current code is not using proper new lines, for example in Notepad you'll see it all as one long line. Change the code to this to have proper new lines:

    string csv = string.Format("{0},{1}{2}", first, image, Environment.NewLine);
    
    0 讨论(0)
提交回复
热议问题