简体   繁体   中英

Exporting MySQL table to csv one row divided in to multiple rows

I am trying to export database table to csv file. However file gets converted & downloading but one single row data is been divided in to many rows which creates problem. Following code I found from aspsnippets which I am using. Is there any problem with kind of records I have which contains HTML tags in.

string constr = ConfigurationManager.ConnectionStrings("conio").ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr)) {
    using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM products")) {
        using (MySqlDataAdapter sda = new MySqlDataAdapter()) {
            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 += Constants.vbCr + Constants.vbLf;

                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 += Constants.vbCr + Constants.vbLf;
                }

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

Snapshot

Highlighted is begining of each row. In between rows created which should be in same row which highlighted. 在此处输入图片说明

csv += "\"" + row(column.ColumnName).ToString().Replace(",", ";") + "\"" + ',';

Change this line in your code and let me know if it helps.

If there are special characters, they should be put inside a double quote.

So, your row should look like below

id,name,htmltags
"1","abcd","<td>values</td>"

Your code should be like

For Each row As DataRow In dt.Rows 
For Each column As DataColumn In dt.Columns 
'Add the Data rows. 
Dim str As String 
str = row(column.ColumnName).ToString() 
str = Replace(str, """", """""") 
csv += """" & str & """" & "," 
Next 

'Add new line. 
csv += vbCr & vbLf 
Next

You need to replace '\\n', '\\t' and extra spaces to "" the same way you did with , and ; using replace() or RegEx and then add it to file.

in C#, it is safe to use Environment.NewLine for output. But when you're extracting from database, you need to check for \\n or \\t as most databases use them as delimiters.

Something like this also works. (its lengthy but works)

csv += row(column.ColumnName).ToString().Replace(",", ";").Replace('\n',"").Replace('\t',"") + ',';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM