Dear All,
I'm newbie
I want export data from store procedure to be .CSV File.
I use code below :
C#
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?

Sachin SinghRank #66 · 26.2K reputationPosted Oct 5, 2023, 6:16 AM EDT
Test this
public static string WriteToCSV(string input) { try { if (input == null) return string.Empty; bool containsQuote = false; bool containsComma = false; int len = input.Length; for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++) { char ch = input[i]; if (ch == '"') containsQuote = true; else if (ch == ',') containsComma = true; } if (containsQuote && containsComma) input = input.Replace("\"", "\"\""); if (containsComma) return "\"" + input + "\""; else return input; } catch { throw; } }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) { StringBuilder sb = new StringBuilder(); foreach (DataRow dr in dt.Rows) { foreach (DataColumn dc in dt.Columns) sb.Append(WriteToCS(dr[dc.ColumnName].ToString()) + ","); sb.Remove(sb.Length - 1, 1); sb.AppendLine(); } File.WriteAllText(@"folderpath\fileName.csv", sb.ToString()); } } } }Santosh KaranamRank #954 · 2.1K reputationPosted Oct 5, 2023, 12:35 PM EDT
You can use csv Helper
public void Generate(SurveyData[] dataList, string fileName) { using (var memoryStream = File.OpenWrite($".\\{fileName}.csv")) { using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8)) { using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture)) { csvWriter.WriteRecords(dataList); csvWriter.Flush(); } } } }Naimish MakwanaRank #324 · 7.7K reputationPosted Oct 6, 2023, 3:34 AM EDT
Example of how you can implement these optimizations:
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; // Use SqlDataReader to stream data using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { 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"; // Use a StringBuilder to build the CSV StringBuilder csvBuilder = new StringBuilder(); // Write column headers for (int i = 0; i < reader.FieldCount; i++) { csvBuilder.Append(reader.GetName(i) + ","); } csvBuilder.AppendLine(); // Stream data while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { csvBuilder.Append(reader[i].ToString().Replace(",", ";") + ","); } csvBuilder.AppendLine(); } // Write the CSV to the response Response.Write(csvBuilder.ToString()); Response.End(); } else { ResinTesterClass.Alert("Data Not Found", this.Page); } } } }Thanks
Naimish Makwana