Link to home
Start Free TrialLog in
Avatar of mohanvamsi_g
mohanvamsi_g

asked on

Export dataset to MS Excel

Hi all

iam trying to export dataset into excel sheet and to be displayed in browser itself. but when i check for the user session, then excel is getting opened and login page is getting displayed. if i comment the code to check user session its working fine.

below is the code snippet...

 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here

        If Session("login") = "" Then
            Response.Redirect("login.aspx")
        End If
             
            Dim dr As SqlClient.SqlDataReader
            cn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
            cmd.Connection = cn
            SqlAdapt.SelectCommand = cmd
            cn.Open()
            fillGrid()
            'Dim ses As String = Session("login")
            DataSetToExcel.Convert(ds, Response) '', " test")
            cn.Close()
       
    End Sub

Public Shared Sub Convert(ByVal ds As DataSet, ByVal res As HttpResponse)
        'first let's clean up the response.object
        res.Clear()
        res.Charset = ""
        'set the response mime type for excel
        res.ContentType = "application/vnd.ms-excel"
       

        'create a string writer
        Dim stringWrite As New System.IO.StringWriter()
        'create an htmltextwriter which uses the stringwriter
        Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
        'instantiate a datagrid
        Dim dg As New DataGrid()
        'set the datagrid datasource to the dataset passed in
        dg.DataSource = ds.Tables(0)

        'bind the datagrid
        dg.DataBind()
        'tell the datagrid to render itself to our htmltextwriter
        dg.RenderControl(htmlWrite)
        'all that's left is to output the html
        res.Write(stringWrite.ToString)
        res.End()
    End Sub

thanks in advance....

regs
Mohan
ASKER CERTIFIED SOLUTION
Avatar of Bharat23
Bharat23

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial