/// <summary> /// 返回列头 /// </summary> /// <param name="template"></param> /// <returns></returns> public List <ExcelHeader> GetHeaderList(string template) { XmlTextReader reader = new XmlTextReader(template); XmlDocument doc = new XmlDocument(); doc.Load(reader); List <ExcelHeader> headerList = new List <ExcelHeader>(); foreach (XmlNode node in doc.DocumentElement.ChildNodes) { ExcelHeader header = new ExcelHeader(); if (node.Attributes["HeaderText"] != null) { header.HeaderText = node.Attributes["HeaderText"].Value; } if (node.Attributes["PropertyName"] != null) { header.PropertyName = node.Attributes["PropertyName"].Value; } if (node.Attributes["DataType"] != null) { header.DataType = node.Attributes["DataType"].Value; } if (node.Attributes["StringFormat"] != null) { header.StringFormat = node.Attributes["StringFormat"].Value; } if (node.Attributes["MappingTo"] != null) { header.MappingTo = node.Attributes["MappingTo"].Value; } if (node.Attributes["Width"] != null) { string width = node.Attributes["Width"].Value; if (Regexlib.MatchInt(width)) { header.Width = int.Parse(width); } } foreach (XmlNode subNode in node.ChildNodes) { header.Mapping.Add(new Mapping { Original = subNode.Attributes["Original"].Value, Target = subNode.Attributes["Target"].Value }); } headerList.Add(header); } return(headerList); }
public T Create <T>(List <ExcelHeader> list, Dictionary <string, object> mapping) { T model = default(T); model = Activator.CreateInstance <T>();//产生一个新的泛型对象 foreach (ExcelHeader header in list) { string value = ""; if (mapping.ContainsKey(header.PropertyName)) { value = mapping[header.PropertyName].ToString(); } string property = header.PropertyName; if (header.Mapping.Count > 0) { value = header.Mapping.Find(s => s.Original == value).Target; property = header.MappingTo; } PropertyInfo prop = model.GetType().GetProperty(property); try { if (prop == null) { continue; } switch (header.DataType) { case "System.Decimal": if (Regexlib.MatchDecimal(value)) { prop.SetValue(model, Convert.ToDecimal(value), null); } break; case "System.Int16": if (Regexlib.MatchInt(value)) { prop.SetValue(model, Convert.ToInt16(value), null); } break; case "System.Int32": if (Regexlib.MatchInt(value)) { prop.SetValue(model, Convert.ToInt32(value), null); } break; case "System.Boolean": if (value != null && value.Length > 0) { prop.SetValue(model, Convert.ToBoolean(value), null); } break; case "System.DateTime": if (Regexlib.MatchDateTime(value)) { prop.SetValue(model, Convert.ToDateTime(value), null); } break; default: prop.SetValue(model, value, null); break; } } catch (Exception ex) { throw new Exception(ex.Message); } } return(model); }