Hi, I am trying to write a file out to an Excel, tab-delimeted file. I do this by going through a datatable, getting the values and creating a tab-delimited string, which I then try to write out. However, when I use the response.write to spit the file out, it writes the string AS WELL AS all the code for the page, the divs/forms/buttons everything. Any ideas? Is there a better way to export excel without having it installed on the web server? Here is the code, how can I get rid of all the page's code in the output...
To generate tab-delimted string:
Thanks,
James
Code:
Try
'execute and fill the dataset
sqlConn.Open()
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblPortfolio")
sqlConn.Close()
'export to excel
Response.ContentType = "application/ms-excel"
Response.AddHeader("Content-Disposition", "inline;filename=Portfolio_" & ds.Tables("tblPortfolio").Rows(0).Item(1).ToString & ".xls")
Dim str_data As String = ""
ConvertDtToTDF(ds.Tables("tblPortfolio"), str_data)
Response.Write(str_data)
Catch ex As Exception
error_label.Text = "There was a problem exporting the portfolio."
End Try
To generate tab-delimted string:
Code:
Private Function ConvertDtToTDF(ByVal dt As DataTable, ByRef str_data As String) As String
Dim dr As DataRow, ary() As Object, i As Integer
Dim iCol As Integer
'Output Column Headers
For iCol = 0 To dt.Columns.Count - 1
str_data += dt.Columns(iCol).ToString & vbTab
Next
str_data += vbCrLf
'Output Data
For Each dr In dt.Rows
ary = dr.ItemArray
For i = 0 To UBound(ary)
str_data += ary(i).ToString & vbTab
Next
str_data += vbCrLf
Next
End Function
Thanks,
James