FileHelpers 用法 z
用FileHelplers导出csv数据:
[DelimitedRecord(",")] [IgnoreEmptyLines()] [ConditionalRecord(RecordCondition.ExcludeIfMatchRegex, "^,+$")] public class FormItemExport { [FieldQuoted(‘"’, QuoteMode.OptionalForBoth)] [FieldNullValue(typeof(string), "")] public string Id; [FieldQuoted(‘"’, QuoteMode.OptionalForBoth)] [FieldNullValue(typeof(string), "")] public string FirstName; [FieldQuoted(‘"’, QuoteMode.OptionalForBoth)] [FieldNullValue(typeof(string), "")] public string LastName; [FieldQuoted(‘"’, QuoteMode.OptionalForBoth)] [FieldNullValue(typeof(string), "")] public string Email; [FieldQuoted(‘"’, QuoteMode.OptionalForBoth)] [FieldNullValue(typeof(string), "")] public string RewardsCardHolder; [FieldQuoted(‘"’, QuoteMode.OptionalForBoth)] [FieldNullValue(typeof(string), "")] public string CreateDatetime; } public class Utils { public delegate V ExportFill<T, V>(T inptOj); public static FormItemExport FillForm(WscLandingFormEntity le) { FormItemExport lre = new FormItemExport(); lre.Id = le.Id.ToString(); lre.FirstName = le.FirstName; lre.LastName = le.LastName; lre.Email = le.Email; if (le.RewardsCardHolder) { lre.RewardsCardHolder = "Yes"; } else { lre.RewardsCardHolder = "No"; } lre.CreateDatetime = le.CreateDatetime.ToString("MM/dd/yyyy hh:mm:ss"); return lre; } public static void Export<T, V>(EntityCollectionBase<T> ec, ExportFill<T, V> expF, string filename, string[] fieldsHeaders) where T : EntityBase { string delimiter = ","; string qualifier = """; List<V> recordCollection = new List<V>(); foreach (T obj in ec) { recordCollection.Add(expF(obj)); } MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); ms.Position = 0; FileHelperEngine engine = new FileHelperEngine(typeof(V)); V[] erc = recordCollection.ToArray(); StringBuilder strOut = new StringBuilder(); for (int i = 0; i < fieldsHeaders.Length; i++) { strOut.Append(qualifier); strOut.Append(fieldsHeaders[i]); strOut.Append(qualifier); if (i < fieldsHeaders.Length – 1) strOut.Append(delimiter); } engine.HeaderText = strOut.ToString(); engine.WriteStream(sw, erc); HttpResponse response = HttpContext.Current.Response; response.Clear(); response.AddHeader("content-disposition", "attachment; filename=" + filename); response.ContentType = "application/vnd.ms-excel"; sw.Flush(); ms.Flush(); ms.WriteTo(response.OutputStream); ms.Close(); response.Flush(); response.End(); } }
导出时:
Utils.Export < MclCommercialContactEntity, CommercialContactExport> (list,new Utils.ExportFill<MclCommercialContactEntity,CommercialContactExport>(CommercialContactExport.ExportCommercialContacts), "Commercial Contacts.csv", new string[] { "Organization", "First Name", "Last Name", "Address", "City", "Province", "Country", "Postal Code", "Phone Number", "Alternate Phone", "Email" });