首页 > 代码库 > list数据源生成csv文件公共类
list数据源生成csv文件公共类
public static class CsvFile
{
public static bool SaveAsCsv<T>(string fileName, IList<T> listModel) where T : class, new()
{
bool flag = false;
try
{
StringBuilder sb = new StringBuilder();
//通过反射 显示要显示的列
BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;//反射标识
Type objType = typeof(T);
PropertyInfo[] propInfoArr = objType.GetProperties(bf);
string header = string.Empty;
List<string> listPropertys = new List<string>();
foreach (PropertyInfo info in propInfoArr)
{
if (String.CompareOrdinal(info.Name.ToUpper(), "ID") != 0) //不考虑自增长的id或者自动生成的guid等
{
if (!listPropertys.Contains(info.Name))
{
listPropertys.Add(info.Name);
}
header += info.Name + ",";
}
}
sb.AppendLine(header.Trim(‘,‘)); //csv头
foreach (T model in listModel)
{
string strModel = string.Empty;
foreach (string strProp in listPropertys)
{
foreach (PropertyInfo propInfo in propInfoArr)
{
if (String.CompareOrdinal(propInfo.Name.ToUpper(), strProp.ToUpper()) == 0)
{
PropertyInfo modelProperty = model.GetType().GetProperty(propInfo.Name);
if (modelProperty != null)
{
object objResult = modelProperty.GetValue(model, null);
string result = (objResult ?? string.Empty).ToString().Trim();
if (result.IndexOf(‘,‘) != -1)
{
result = "\"" + result.Replace("\"", "\"\"") + "\""; //特殊字符处理 ?
//result = result.Replace("\"", "“").Replace(‘,‘, ‘,‘) + "\"";
}
if (!string.IsNullOrEmpty(result))
{
Type valueType = modelProperty.PropertyType;
if (valueType == typeof(decimal?))
{
result = decimal.Parse(result).ToString("#.#");
}
else if (valueType == typeof(decimal))
{
result = decimal.Parse(result).ToString("#.#");
}
else if (valueType == typeof(double?))
{
result = double.Parse(result).ToString("#.#");
}
else if (valueType == typeof(double))
{
result = double.Parse(result).ToString("#.#");
}
else if (valueType == typeof(float?))
{
result = float.Parse(result).ToString("#.#");
}
else if (valueType == typeof(float))
{
result = float.Parse(result).ToString("#.#");
}
}
strModel += result + ",";
}
else
{
strModel += ",";
}
break;
}
}
}
strModel = strModel.Substring(0, strModel.Length - 1);
sb.AppendLine(strModel);
}
string content = sb.ToString();
string dir = Directory.GetCurrentDirectory();
string fullName = Path.Combine(dir, fileName);
if (File.Exists(fullName)) File.Delete(fullName);
using (FileStream fs = new FileStream(fullName, FileMode.CreateNew, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
sw.Flush();
sw.Write(content);
sw.Flush();
sw.Close();
}
flag = true;
}
catch
{
flag = false;
}
return flag;
}
}
list数据源生成csv文件公共类