我正在尝试将数据库表导出到csv文件。然而,文件被转换&下载但是单行数据被划分为多行,这会产生问题。以下代码我从aspsnippets找到了我正在使用的代码。我所拥有的包含HTML标签的记录是否存在任何问题。
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();
}
}
}
}
快照
答案 0 :(得分:1)
csv += "\"" + row(column.ColumnName).ToString().Replace(",", ";") + "\"" + ',';
在代码中更改此行,如果有帮助,请告诉我。
如果有特殊字符,则应将它们放在双引号内。
因此,您的行应如下所示
id,name,htmltags
"1","abcd","<td>values</td>"
您的代码应该像
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
答案 1 :(得分:0)
您需要将'\n', '\t'
和额外空格替换为""
,方法与此相同,并且;使用replace()或RegEx,然后将其添加到文件中。
在C#中,使用Environment.NewLine输出是安全的。但是当您从数据库中提取时,您需要检查\n
或\t
,因为大多数数据库都将它们用作分隔符。
这样的东西也有效。 (它冗长但有效)
csv += row(column.ColumnName).ToString().Replace(",", ";").Replace('\n',"").Replace('\t',"") + ',';