Link to home
Start Free TrialLog in
Avatar of mugsey
mugseyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Convert datareader to CSV and export to web browser in ASP.NET C#

I have a datareader

while (thisReader.Read())
{
}

Now how can I export the contents of this datarader to a web browser in CSV format, so the user can save the file on this desktop.

Avatar of Pratima
Pratima
Flag of India image

Try this
 //Add Response header 
        Response.Clear();
        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        //GET Data From Database                
        SqlConnection cn = new SqlConnection(dataSrc.ConnectionString);
        string query = dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
        
        SqlCommand cmd = new SqlCommand(query, cn);
        
        cmd.CommandTimeout = 999999 ;
        cmd.CommandType    = CommandType.Text;
        try
        {
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            StringBuilder sb = new StringBuilder();            
            //Add Header          
            for (int count = 0; count < dr.FieldCount; count++)
            {
                if (dr.GetName(count) != null)
                    sb.Append(dr.GetName(count));
                if (count < dr.FieldCount - 1)
                {
                    sb.Append(",");
                }
            }
            Response.Write(sb.ToString() + "\n");
            Response.Flush();            
            //Append Data
            while (dr.Read())
            {
                sb = new StringBuilder();
               
                for (int col = 0; col < dr.FieldCount - 1; col++)
                {
                    if (!dr.IsDBNull(col))
                        sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
                    sb.Append(",");
                }
                if (!dr.IsDBNull(dr.FieldCount - 1))
                    sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "));
                Response.Write(sb.ToString() + "\n");
                Response.Flush();
            }
            dr.Dispose();

Open in new window

Try this:

private string ToCSV(DataTable dataTable)
{
 
  DataTable schemaTable = myReader.GetSchemaTable();
 
  StringBuilder sb = new StringBuilder();      
  foreach (DataColumn column in schemaTable.Columns)
  {
    sb.Append(column.ColumnName + ',');
  }            
 
  sb.Append("\r\n");
      
  foreach (DataRow row in schemaTable.Rows)
  {
    foreach (DataColumn column in schemaTable.Columns)
    {
      sb.Append(row[column].ToString() + ',');
    }                  
    sb.Append("\r\n");
  }      
  return sb.ToString();
}

Open in new window

Avatar of mugsey

ASKER

OK thanks guys I will try in the next hour
Avatar of mugsey

ASKER

Thanks pratima_mcs

How can I specify the file name and where to save the file?  Thanks
When you run this code it will ask with a popup to open , save
Avatar of mugsey

ASKER

OK thanks - so you know the line

Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));

Where does filename come from?

You see my code is like this

Currently I have a datareader that is populated from a dynamic search

  while (thisReader.Read())
                {
                 

                }

How can I amend your code above so it works



Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));

in this they have used the parament send to the function ...

you can use your own tempory file name there like

Response.AddHeader("content-disposition", string.Format("attachment;filename=temp.csv", fileName));

that will appear by default in save dialog
Avatar of mugsey

ASKER

OK thANKS

But could you amend your example so it wiould fit into the following?

while (thisReader.Read())
                {
                 

                }



ASKER CERTIFIED SOLUTION
Avatar of Pratima
Pratima
Flag of India 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