Click here to Skip to main content
14,827,034 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Sir/Madam,
First I bind a data into datagrid, this data is displayed in .csv file how to do this? I am try but if long text is displayed in datagrid that time in csv file it take 2 or 3 lines but my aim is if user enter long text that time also it display in single line.
And if i open this csv file in wordpad that time it display comma to last column also. My aim is comma is not displayed for last column.

My code:

Private Function ToCSV(ByVal dataTable As DataTable) As String 
Dim sb As New StringBuilder() 
If dataTable.Columns.Count <> 0 Then 
For Each column As DataColumn In dataTable.Columns 
sb.Append("," & column.ColumnName) 
Next 
sb.Remove(0, 1) 
sb.Append(vbCr & vbLf) 
For Each row As DataRow In dataTable.Rows 
For Each column As DataColumn In dataTable.Columns 
sb.Append(row(column).ToString() + ","c) 
Next 
sb.Append(vbCrLf) 
Next 
End If 
Return sb.ToString() 
End Function 

and in button click
'// here i bind datagrid
and then
Response.ContentType = "Application/x-msexcel" 
Response.AddHeader("content-disposition", "attachment;filename=Reports.csv") 
Response.Write(ToCSV(tdata)) 
Response.[End]() 


Please help me.
Thanks.
Posted
Updated 17-Aug-10 2:39am
v2

1 solution

Try modifying your ToCSV() function like this:
Private Function ToCSV(ByVal dataTable As DataTable) As String
    Dim sb As New StringBuilder()
    If dataTable.Columns.Count <> 0 Then
        For Each column As DataColumn In dataTable.Columns
            sb.Append("," & column.ColumnName)
        Next
        sb.Remove(0, 1)
        sb.Append(vbCr & vbLf)
        For Each row As DataRow In dataTable.Rows
            For I As Integer = 0 To dataTable.Columns.Count - 1
                Dim column As DataColumn = dataTable.Columns(I)
                If I <> dataTable.Columns.Count - 1 Then
                    sb.Append(row(column).ToString() + ","c)
                Else
                    sb.Append(row(column).ToString())
                End If
            Next
            sb.Append(vbCrLf)
        Next
    End If
    Return sb.ToString()
End Function
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900