Click here to Skip to main content
14,845,771 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:

  1  Private Function ToCSV(ByVal dataTable As DataTable) As String 
  2  Dim sb As New StringBuilder() 
  3  If dataTable.Columns.Count <> 0 Then 
  4  For Each column As DataColumn In dataTable.Columns 
  5  sb.Append("," & column.ColumnName) 
  6  Next 
  7  sb.Remove(0, 1) 
  8  sb.Append(vbCr & vbLf) 
  9  For Each row As DataRow In dataTable.Rows 
 10  For Each column As DataColumn In dataTable.Columns 
 11  sb.Append(row(column).ToString() + ","c) 
 12  Next 
 13  sb.Append(vbCrLf) 
 14  Next 
 15  End If 
 16  Return sb.ToString() 
 17  End Function 

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


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

1 solution

Try modifying your ToCSV() function like this:
  1  Private Function ToCSV(ByVal dataTable As DataTable) As String
  2      Dim sb As New StringBuilder()
  3      If dataTable.Columns.Count <> 0 Then
  4          For Each column As DataColumn In dataTable.Columns
  5              sb.Append("," & column.ColumnName)
  6          Next
  7          sb.Remove(0, 1)
  8          sb.Append(vbCr & vbLf)
  9          For Each row As DataRow In dataTable.Rows
 10              For I As Integer = 0 To dataTable.Columns.Count - 1
 11                  Dim column As DataColumn = dataTable.Columns(I)
 12                  If I <> dataTable.Columns.Count - 1 Then
 13                      sb.Append(row(column).ToString() + ","c)
 14                  Else
 15                      sb.Append(row(column).ToString())
 16                  End If
 17              Next
 18              sb.Append(vbCrLf)
 19          Next
 20      End If
 21      Return sb.ToString()
 22  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