Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6955483
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T14:44:31+00:00 2026-05-27T14:44:31+00:00

I am trying to export a list of table to comma-separated value(CSV) .but not

  • 0

I am trying to export a list of table to comma-separated value(CSV) .but not getting the correct output .output coming from this code is in the form of html table.
Here is my code,Help Me ….
Thanks

      public void ExportToCsv()
      {

      DataClassesDataContext db = new DataClassesDataContext();
      var employee = db.Employees.ToList();
      var grid = new System.Web.UI.WebControls.GridView();
      grid.DataSource = employee;
      grid.DataBind();

      StringBuilder strbldr = new StringBuilder();

      for (int i = 0; i < grid.Columns.Count; i++)
        {
            strbldr.Append(grid.Columns[i].HeaderText + ',');
        }
        for (int j = 0; j < grid.Rows.Count; j++)
        {
            for (int k = 0; k < grid.Columns.Count; k++)
            {
                //separating gridview columns with comma
                strbldr.Append(grid.Rows[j].Cells[k].Text + ',');
            }
            //appending new line for gridview rows
            strbldr.Append("\n");
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=YourFileName.csv");
        Response.ContentType = "text/csv";
        StringWriter sa = new StringWriter(strbldr);
        HtmlTextWriter ht = new HtmlTextWriter(sa);
        grid.RenderControl(ht);
        Response.Write(sa.ToString());
        Response.End();
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T14:44:32+00:00Added an answer on May 27, 2026 at 2:44 pm

    I think First you convert your list to datatable by using below code

    public static DataTable ToDataTable<T>(List<T> l_oItems)
        {
            DataTable oReturn = new DataTable(typeof(T).Name);
            object[] a_oValues;
            int i;
    
            //#### Collect the a_oProperties for the passed T
            PropertyInfo[] a_oProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    
            //#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
            //####     NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
            foreach (PropertyInfo oProperty in a_oProperties)
            {
                oReturn.Columns.Add(oProperty.Name, BaseType(oProperty.PropertyType));
            }
    
            //#### Traverse the l_oItems
            foreach (T oItem in l_oItems)
            {
                //#### Collect the a_oValues for this loop
                a_oValues = new object[a_oProperties.Length];
    
                //#### Traverse the a_oProperties, populating each a_oValues as we go
                for (i = 0; i < a_oProperties.Length; i++)
                {
                    a_oValues[i] = a_oProperties[i].GetValue(oItem, null);
                }
    
                //#### .Add the .Row that represents the current a_oValues into our oReturn value
                oReturn.Rows.Add(a_oValues);
            }
    
            //#### Return the above determined oReturn value to the caller
            return oReturn;
        }
    
        private static Type BaseType(Type oType)
        {
            //#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
            if (oType != null && oType.IsValueType &&
                oType.IsGenericType && oType.GetGenericTypeDefinition() == typeof(Nullable<>)
            )
            {
                return Nullable.GetUnderlyingType(oType);
            }
            //#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
            else
            {
                return oType;
            }
        }
    

    Then Use below code for export datatable to csv..

    public static string ToCSV(DataTable dataTable)
        {
            //create the stringbuilder that would hold the data
            StringBuilder sb = new StringBuilder();
            //check if there are columns in the datatable
            if (dataTable.Columns.Count != 0)
            {
                //loop thru each of the columns for headers
                foreach (DataColumn column in dataTable.Columns)
                {
                    //append the column name followed by the separator
                    sb.Append(column.ColumnName + ",");
                }
                //append a carriage return
                sb.Append("\r\n");
    
                //loop thru each row of the datatable
    
                foreach (DataRow row in dataTable.Rows)
                {
                    //loop thru each column in the datatable
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        //get the value for the row on the specified column
                        // and append the separator
                        sb.Append("\"" + row[column].ToString() + "\"" + ",");
                    }
                    //append a carriage return
                    sb.Append("\r\n");
                }
            }
            return (sb.ToString());
        }
    

    Main Function is : This

    DataTable dt = GeneralFunctions.ToDataTable(HereputyourlistforcovertToDataTable);
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            Response.Clear();
                            Response.ClearHeaders();
                            Response.ClearContent();
                            Response.ContentType = "text/CSV";
                            Response.AddHeader("content-disposition", "attachment; filename=ReceivingLog.csv");
                            Response.Write(ToCSV(dt));
                            Response.End();
                        }
                    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im trying to export a .dmp of an oracle database but am getting the
I am trying to export from SQL to .csv and it works if I
I am trying to export a list to a CSV file. I got it
Recently i was trying to export my friends' birthday's list from facebook, where i
I am trying to create a CSV file from a dynamically generated table.I have
I'm trying to export a list of changed files from two commits with git,
I am trying to export the following data in the query from ms sql
I'm trying to export a copy of the Explain Plan from Oracle SQL Developer
I'm trying to export a profile from WAS 6.1 so that I can give
I'm trying to export records from SQL Server 2008 to mdb file using OpenDataSource.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.