private IList <string> GetContentCSV(ExportParameter.CSV parameter) { IList <string> list = new List <string>(); // header string _header = string.Empty; foreach (PropertyDescriptor header in parameter.HeaderExport) { _header += header.DisplayName + ","; } list.Add(_header); // body foreach (var item in parameter.BodyExport) { string _body = string.Empty; foreach (PropertyDescriptor header in parameter.HeaderExport) { var _value = header.GetValue(item) ?? DBNull.Value; _body += MakeValueCSV(_value) + ","; } list.Add(_body); } return(list); }
// set parameter for export to csv public ExportParameter.CSV SetReportParameter(string filename, PropertyDescriptorCollection headerExport, IEnumerable <object> BodyExport) { try { if (string.IsNullOrEmpty(filename)) { throw new Exception("Filename to export is not null or empty."); } if (headerExport == null) { throw new Exception("Data invalid."); } var parameter = new ExportParameter.CSV() { FileName = filename, HeaderExport = headerExport, BodyExport = BodyExport }; return(parameter); } catch (Exception ex) { throw ex; } }
// Export to csv public void ExportToCSV(ExportParameter.CSV parameter) { try { if (parameter == null) { throw new Exception("parameter to export is not null."); } string filename = parameter.FileName; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "text/plain"; HttpContext.Current.Response.Charset = "windows-874"; // ระบบปลายทางต้องการ format UNIX ANSI จึงต้องใช้ windows-874 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(874); HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", filename)); IList <string> contents = GetContentCSV(parameter); using (StreamWriter sw = new StreamWriter(HttpContext.Current.Response.OutputStream, Encoding.Default)) { foreach (string content in contents) { sw.WriteLine(content); } } HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (Exception ex) { throw ex; } }