Cómo generar todas las columnas con comillas dobles en la exportación csv usando vb.net
Frecuentes
Visto 2,024 veces
2
I generate csv content type export.
added columns like "A","B","C","D" by
columns = string.format("""{0}"",""{1}"",""{2}""","A","B","C")
stream.writeline(columns);
the csv file was exported but the first column don't having the double quotes. i need double quote with every column. i tried so many ways with in that one of the way is working fine that is columns = string.format(" ""{0}"",""{1}"",""{2}""","A","B","C") -- put space before first column.
but i need result without space.
any one can help to fix this.
Código de muestra:
Public Class CSVExporter
Public Shared Sub WriteToCSV(personList As List(Of Person))
Dim attachment As String = "attachment; filename=PerosnList.csv"
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.AddHeader("content-disposition", attachment)
HttpContext.Current.Response.ContentType = "text/csv"
HttpContext.Current.Response.AddHeader("Pragma", "public")
WriteColumnName()
For Each item As Person In personList
WriteUserInfo(item)
Next
HttpContext.Current.Response.[End]()
End Sub
Private Shared Sub WriteUserInfo(item As Person)
Dim strb As New StringBuilder()
AddComma(String.Format("""{0}""", item.Name), strb)
AddComma(String.Format("""{0} """, item.Family), strb)
AddComma(String.Format("""{0} """, item.Age.ToString()), strb)
AddComma(String.Format("""{0:C2}""", item.Salary), strb)
HttpContext.Current.Response.Write(strb)
HttpContext.Current.Response.Write(Environment.NewLine)
End Sub
Private Shared Sub AddComma(item As String, strb As StringBuilder)
strb.Append(item.Replace(",", " "))
strb.Append(" ,")
End Sub
Private Shared Sub WriteColumnName()
Dim str As String = """Name"", ""Family"", ""Age"", ""Salary"""
HttpContext.Current.Response.Write(str)
HttpContext.Current.Response.Write(Environment.NewLine)
End Sub
End Class
I'm not sure I follow. Your first example
string.format("""{0}"",""{1}"",""{2}""","A","B","C")
producido"A","B","C"
, but you say the first column didn't have double-quotes. But it did. Can you clarify the issue a little bit? - LarsTechonce i put space before first column(" ""{0}"") - i can see the first column with quotes in csv file. - user571488
the string format result also correct. like (""A","B","C""). please help to fix this. - user571488
I could only guess that the HttpContext classes somehow don't like that first double-quote when creating that attachment. - LarsTech
yes you are rite. but how to fix it? it's look like a simple thing but it's already taken my 6 hrs. :) - user571488