Abay Muslimin

Abay Muslimin

  • 1.7k
  • 36
  • 523

Convert to CSV (not efficient)

Oct 5 2023 9:16 AM

Dear All,

I'm newbie

I want export data from store procedure to be .CSV File.

I use code below :

SP_ValueCPK = "[SP_CPK_VALUE_DOWNLOAD_CSV]  '" + Dept+"','"+ PeriodeAwal+ "','" + PeriodeAkhir + "','"+ IDProductType + "' ";
using (SqlCommand cmd = new SqlCommand(SP_ValueCPK))
{
    using (SqlDataAdapter sda = new SqlDataAdapter())
    {
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        using (DataTable dt = new DataTable())
        {

            sda.Fill(dt);

            if (dt.Rows.Count > 0)
            {

                //Build the CSV file data as a Comma separated string.
                string csv = string.Empty;

                foreach (DataColumn column in dt.Columns)
                {
                    //Add the Header row for CSV file.
                    csv += column.ColumnName + ',';
                }

                //Add new line.
                csv += "\r\n";

                foreach (DataRow row in dt.Rows)
                {
                    foreach (DataColumn column in dt.Columns)
                    {
                        //Add the Data rows.
                        csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                    }

                    //Add new line.
                    csv += "\r\n";
                }

                //Download the CSV file.
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=" + this.DropDownListDept.SelectedValue + " - Value of CPK (" + this.LabelPeriodeNow.Text + " - " + this.LabelPeriodeLast.Text + ").csv");

                Response.Charset = "";
                Response.ContentType = "application/text";  
                Response.Output.Write(csv);  
                Response.Flush();
                Response.End();
            }
            else
            {
                ResinTesterClass.Alert("Data Not Found", this.Page);
            }
        }
    }
}

but, if i use this code.

very long wait if it have 500 rows data .

maybe, is there a solution to solve it?


Answers (3)