Exporting in Excel using Response.ContentType = "application/ms-excel"

  • Thread starter Microsoft NewsGroups
  • Start date
M

Microsoft NewsGroups

I am creating a TAB delimited file with .XLS extention using the Response.ContentType = "application/ms-excel" method. Normally I would place this on it's own form and delete all the HTML in the ASPX page - otherwise the aspx code gets appended to the end of the file out put to Excel. How do I produce the same output from a page where I cannot simply delete all the HTML code (must leave buttons and other objects intact)? In other words how can I keep the aspx code from being appended to the file that is sent to the client?

Here is the pertinent code (adapted from article by Steve C. Orr):

If custConnection.State = ConnectionState.Closed Then
custConnection.ConnectionString = "data source=OURSERVERINFOHERE;initial catalog=DB_NAME;integrated security=SSPI"
custConnection.Open()
End If
custAdapterCommand = New SqlClient.SqlDataAdapter("SELECT * FROM tMAIN WHERE DivisionDeptID = " & TextBox1.Text.ToString, custConnection)
custAdapterCommand.Fill(custDataSet, "tMain")
Response.ContentType = "application/ms-excel"
Response.AddHeader("Content-Disposition", "inline;filename=test.xls")
Response.Write(ConvertDtToTDF(custDataSet))

Private Function ConvertDtToTDF(ByVal dt As DataSet) As String
Dim dr As DataRow, ary() As Object, i As Integer
Dim iCol As Integer

'Output Column Headers
For iCol = 0 To dt.Tables(0).Columns.Count - 1
Response.Write(dt.Tables(0).Columns(iCol).ColumnName.ToString & vbTab)
Next
Response.Write(vbCrLf)

'Output Data
Dim aText As String = "" ' TESTING
For Each dr In dt.Tables(0).Rows
ary = dr.ItemArray
For i = 0 To UBound(ary)
'Response.Write(ary(i).ToString & vbTab)
aText += ary(i).ToString & vbTab
Next
'Response.Write(vbCrLf)
aText += vbCrLf
Next
Return aText
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top