Link to home
Start Free TrialLog in
Avatar of strickdd
strickddFlag for United States of America

asked on

Data reader to CSV

I need a web page in C# that will take the results from the execution of a stored procedure and create an Excel compatible .csv file and prompt the user to download it. Is there a way to do this on the fly?
Avatar of deanvanrooyen
deanvanrooyen

does this help
http://www.codeproject.com/Purgatory/Exporting_Dataset_ASPNet.asp

can xl read xml?

cause you could just write the dataset to xml - it already supports that...

        DataSet ds = new DataSet();
        //fill dataset
        ds.WriteXml("filename.xml");
ASKER CERTIFIED SOLUTION
Avatar of Sammy
Sammy
Flag of Canada image

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
Avatar of YZlat
here is a function to which you'll have to pass the path to the file you want to write to and a datatable object with data from database:

Public Sub WriteDataToCSV(ByVal path As String, ByVal dt As System.Data.DataTable)
        Dim delim As String
        Dim sw As StreamWriter

        ' Write out the header row
        delim = ""
        Try
            sw = New StreamWriter(path, False, UnicodeEncoding.Default)
            For Each col As DataColumn In dt.Columns
                sw.Write(delim)
                sw.Write(col.ColumnName)

                delim = ","
            Next
            sw.WriteLine()

            ' write out each data row
            For Each row As DataRow In dt.Rows
                delim = ""
                For Each value As Object In row.ItemArray
                    sw.Write(delim)
                    If TypeOf value Is String Then
                        sw.Write(""""c) ' thats four double quotes and a c
                        sw.Write(value)

                        sw.Write(""""c) ' thats four double quotes and a c
                    Else
                        sw.Write(value)
                    End If
                    delim = ","
                Next
                sw.WriteLine()
            Next
        Catch ex As Exception
            Console.Write("ERROR: " & ex.Message)
        Finally
            sw.Close()
        End Try

    End Sub