Sometimes when you save Excel data to a CSV file, a CSV format error occurs, and the following example implements the data stored in the DataTable directly to a CSV file.
system.web.httpruntime.cache["v_ds" "";
This v_ds is a cache, because sometimes because the page refresh will empty the memory of the data, here with the cache, of course, there are many other ways.
DataTable dt = (DataTable) system.web.httpruntime.cache["V_ds"]; Response.clearcontent (); Response.AddHeader ("content-disposition","attachment; Filename="+ DateTime.Now.ToString ("YYYY-MM-DD") +". csv"); Response.ContentEncoding= System.Text.Encoding.GetEncoding ("gb2312"); Response.ContentType="Application/excel"; StringBuilder SB=NewStringBuilder (); Sb. Append ("ticket, pallet number, box number, SN,IMEID1,IMEID2, customer po\r\n"); for(inti =0; i < dt. Rows.Count; i++) {sb. Append ("\""+ dt. rows[i]["Ticket number"] +"\""+","); Sb. Append ("\""+ dt. rows[i]["Stack Plate number"] +"\""+","); Sb. Append ("\""+ dt. rows[i]["Medium Container No."] +"\""+","); Sb. Append ("\""+ dt. rows[i]["SN"] +"\""+","); Sb. Append ("\""+ dt. rows[i]["IMEID1"] +"\""+","); Sb. Append ("\""+ dt. rows[i]["IMEID2"] +"\""+","); Sb. Append ("\""+ dt. rows[i]["Customer PO"] +"\""+"\ r \ n"); } Response.Write (sb.) ToString ()); Response.End ();
C # Export data to CSV