开发者

How to avoid error when exporting csv file containing commas?

Currently I have this codes:

 SqlConnection connection = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
        SqlCommand Command = connection.CreateCommand();

        SqlDataReader SQLRD;

        Command.CommandText = "Select * from Attendance";

        connection.Open();
        SQLRD = Command.ExecuteReader();


        //string data = "";

        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        while (SQLRD.Read())
        {

            sb.Append(String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}\n",
            SQLRD[0], SQLRD[1], SQLRD[2], SQLRD[3], SQLRD[4], SQLRD[5], SQLRD[6], SQLRD[7]));
        }

        SQLRD.Close();
        connection.Close();

        byte[] ar = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content.Type", "application/octet-stream");
        Response.AddHeader("Content-Length", ar.Length.ToString());
        Response.AddHeader("Content-Disposition", "attachment; filename=download.csv");
        Response.BinaryWrite(ar);
        Response.Flush();
        Response.End();

Currently, if I export it, and if there are commas in the string, it would be in another column of the csv file, and not same as the others, how can I solve this? 开发者_Go百科Hope someone can help me!


The CSV "spec" (if you can call it that) allows for text qualifiers. So, you can do the following:

test,test,"this, and this", test

That's four columns of data with the third containing the value [this, and this].

Edit: Modify your format string to the following:

"\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\"\n"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜