开源项目 10 CSV
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApp2.test1
{
public class Class10
{
public void test1()
{
var dt = CSVFileHelper.OpenCSV(@"1.csv"); dt.Columns["联系人姓名"].ColumnName = "Name";
dt.Columns["备注"].ColumnName = "Remark"; var list = dt.DataTableToEntities<Crm_Cm_ContactInfo2>(); Console.WriteLine(dt.Rows.Count);
Console.WriteLine(JsonConvert.SerializeObject(list));
}
} public class Crm_Cm_ContactInfo2
{
public string Name { get; set; }
public string Remark { get; set; }
} public class CSVFileHelper
{
/// <summary>
/// 将DataTable中数据写入到CSV文件中
/// </summary>
/// <param name="dt">提供保存数据的DataTable</param>
/// <param name="fileName">CSV的文件路径</param>
public static void SaveCSV(DataTable dt, string fullPath)
{
FileInfo fi = new FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
string data = "";
//写出列名称
for (int i = ; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - )
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = ; i < dt.Rows.Count; i++)
{
data = "";
for (int j = ; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.Format("\"{0}\"", str);
} data += str;
if (j < dt.Columns.Count - )
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
} /// <summary>
/// 将CSV文件的数据读取到DataTable中
/// </summary>
/// <param name="fileName">CSV文件路径</param>
/// <returns>返回读取了CSV数据的DataTable</returns>
public static DataTable OpenCSV(string filePath)
{
Encoding encoding = Encoding.Default; //Encoding.ASCII;//Common.GetType(filePath)
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); //StreamReader sr = new StreamReader(fs, Encoding.UTF8);
StreamReader sr = new StreamReader(fs, encoding);
//string fileContent = sr.ReadToEnd();
//encoding = sr.CurrentEncoding;
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine = null;
string[] tableHead = null;
//标示列数
int columnCount = ;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
//strLine = Common.ConvertStringUTF8(strLine, encoding);
//strLine = Common.ConvertStringUTF8(strLine); if (IsFirst == true)
{
tableHead = strLine.Split(',');
IsFirst = false;
columnCount = tableHead.Length;
//创建列
for (int i = ; i < columnCount; i++)
{
DataColumn dc = new DataColumn(tableHead[i]);
dt.Columns.Add(dc);
}
}
else
{
aryLine = strLine.Split(',');
DataRow dr = dt.NewRow();
for (int j = ; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}
if (aryLine != null && aryLine.Length > )
{
dt.DefaultView.Sort = tableHead[] + " " + "asc";
} sr.Close();
fs.Close();
return dt;
}
} /// <summary>
/// 反射类
/// </summary>
public static class MyReflection
{
/// <summary>
/// DataTable 转换为 对象List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> DataTableToEntities<T>(this DataTable dt) where T : class, new()
{
if (null == dt || dt.Rows.Count == ) { return null; }
List<T> entities = new List<T>(); foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = typeof(T).GetProperties();
T entity = new T(); Array.ForEach<PropertyInfo>(pArray, p =>
{
object cellvalue = row[p.Name];
if (cellvalue != DBNull.Value)
{
//经过了几个版本的迭代,最后一个为最新的,摘自网上,已附原文地址 //4、原地址:https://blog.csdn.net/Simon1003/article/details/80839744
if (!p.PropertyType.IsGenericType)
{
p.SetValue(entity, Convert.ChangeType(cellvalue, p.PropertyType), null);
}
else
{
Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
p.SetValue(entity, Convert.ChangeType(cellvalue, Nullable.GetUnderlyingType(p.PropertyType)), null);
}
else
{
throw new Exception("genericTypeDefinition != typeof(Nullable<>)");
}
} //3、原地址:https://blog.csdn.net/hebbers/article/details/78957569
//Type type = p.PropertyType;
//if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类
//{
// //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
// System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
// //将type转换为nullable对的基础基元类型
// type = nullableConverter.UnderlyingType;
//}
//p.SetValue(entity, Convert.ChangeType(cellvalue, type), null); //2、自定义 这种很傻,但当前解决速度最快
//if (p.PropertyType.Name.Equals("Int32"))
//{
// p.SetValue(entity, Convert.ToInt32(value), null);
//}
//else if (p.PropertyType.Name.Equals("String"))
//{
// p.SetValue(entity, Convert.ToString(value), null);
//}
//else if (p.PropertyType.Name.Equals("Nullable`1"))
//{
// p.SetValue(entity, Convert.ToInt32(value), null);
//}
////其它类型 暂时不管 //1、字段不为空可以用这种
//p.SetValue(entity, value, null);
}
});
entities.Add(entity);
}
return entities;
} public static List<T> DataTableToEntities2<T>(this DataTable dt) where T : class, new()
{
if (null == dt || dt.Rows.Count == ) { return null; }
List<T> entities = new List<T>(); foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = typeof(T).GetProperties();
T entity = new T(); Array.ForEach<PropertyInfo>(pArray, p =>
{
object cellvalue = row[p.Name];
if (cellvalue != DBNull.Value)
{
if (!p.PropertyType.IsGenericType)
{
p.SetValue(entity, Convert.ChangeType(cellvalue, p.PropertyType), null);
}
else
{
Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
p.SetValue(entity, Convert.ChangeType(cellvalue, Nullable.GetUnderlyingType(p.PropertyType)), null);
}
else
{
throw new Exception("genericTypeDefinition != typeof(Nullable<>)");
}
}
}
});
entities.Add(entity);
}
return entities;
} public static List<T> DataTableToEntities3<T>(DataTable dt) where T : class, new()
{
if (null == dt || dt.Rows.Count == ) { return null; }
List<T> entities = new List<T>(); foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = typeof(T).GetProperties();
T entity = new T(); Array.ForEach<PropertyInfo>(pArray, p =>
{
object cellvalue = row[p.Name];
if (cellvalue != DBNull.Value)
{
//经过了几个版本的迭代,最后一个为最新的,摘自网上,已附原文地址 //4、原地址:https://blog.csdn.net/Simon1003/article/details/80839744
if (!p.PropertyType.IsGenericType)
{
p.SetValue(entity, Convert.ChangeType(cellvalue, p.PropertyType), null);
}
else
{
Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
p.SetValue(entity, Convert.ChangeType(cellvalue, Nullable.GetUnderlyingType(p.PropertyType)), null);
}
else
{
throw new Exception("genericTypeDefinition != typeof(Nullable<>)");
}
} //3、原地址:https://blog.csdn.net/hebbers/article/details/78957569
//Type type = p.PropertyType;
//if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类
//{
// //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
// System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
// //将type转换为nullable对的基础基元类型
// type = nullableConverter.UnderlyingType;
//}
//p.SetValue(entity, Convert.ChangeType(cellvalue, type), null); //2、自定义 这种很傻,但当前解决速度最快
//if (p.PropertyType.Name.Equals("Int32"))
//{
// p.SetValue(entity, Convert.ToInt32(value), null);
//}
//else if (p.PropertyType.Name.Equals("String"))
//{
// p.SetValue(entity, Convert.ToString(value), null);
//}
//else if (p.PropertyType.Name.Equals("Nullable`1"))
//{
// p.SetValue(entity, Convert.ToInt32(value), null);
//}
////其它类型 暂时不管 //1、字段不为空可以用这种
//p.SetValue(entity, value, null);
}
});
entities.Add(entity);
}
return entities;
} /// <summary>
/// 跟属性赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="name"></param>
/// <param name="value"></param>
public static void AssignValueToAttribute<T>(T model, string name, object value)
{
Type t = model.GetType();
var p = t.GetProperty(name); if (!p.PropertyType.IsGenericType)
{
p.SetValue(model, Convert.ChangeType(value, p.PropertyType), null);
}
else
{
Type genericTypeDefinition = p.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
p.SetValue(model, Convert.ChangeType(value, Nullable.GetUnderlyingType(p.PropertyType)), null);
}
else
{
throw new Exception("genericTypeDefinition != typeof(Nullable<>)");
}
}
} /// <summary>
/// 获取属性值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="name"></param>
/// <returns></returns>
public static object GetValueByAttribute<T>(T model, string name)
{
Type t = model.GetType();
var p = t.GetProperty(name);
return p.GetValue(model, null);
} /// <summary>
/// 跟属性赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="name"></param>
/// <param name="model_old"></param>
public static void AssignValueToAttribute<T>(T model, string name, T model_old)
{
Type t = model_old.GetType();
var p = t.GetProperty(name);
object obj = p.GetValue(model_old, null); AssignValueToAttribute(model, name, obj);
} }
}
开源项目 10 CSV的更多相关文章
- 【开源项目10】安卓图表引擎AChartEngine
安卓图表引擎AChartEngine(一) - 简介 http://blog.csdn.net/lk_blog/article/details/7645509 安卓图表引擎AChartEngine(二 ...
- Golang优秀开源项目汇总, 10大流行Go语言开源项目, golang 开源项目全集(golang/go/wiki/Projects), GitHub上优秀的Go开源项目
Golang优秀开源项目汇总(持续更新...)我把这个汇总放在github上了, 后面更新也会在github上更新. https://github.com/hackstoic/golang-open- ...
- .NET平台开源项目速览(10)FluentValidation验证组件深入使用(二)
在上一篇文章:.NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(一) 中,给大家初步介绍了一下FluentValidation验证组件的使用情况.文章从构建间的验证器开 ...
- 学习Swift,一定不能错过的10大开源项目!
如果你是位iOS开发者,或者你正想进入该行业,那么Swift为你提供了一个绝佳的机会.Swift的设计非常优雅,较Obj-C更易于学习,当然也非常强大. 为了指导开发者使用Swift进行开发,苹果发布 ...
- 转:程序员最值得关注的10个C开源项目
程序员最值得关注的10个C开源项目 1. Webbench Webbench 是一个在 linux 下使用的非常简单的网站压测工具.它使用 fork ()模拟多个客户端同时访问我们设定的 URL,测试 ...
- [ionic开源项目教程] - 第10讲 新闻详情页的用户体验优化
目录 [ionic开源项目教程] 第1讲 前言,技术储备,环境搭建,常用命令 [ionic开源项目教程] 第2讲 新建项目,架构页面,配置app.js和controllers.js [ionic开源项 ...
- Android开发者必须深入学习的10个应用开源项目
Android 开发又将带来新一轮热潮,很多开发者都投入到这个浪潮中去了,创造了许许多多相当优秀的应用.其中也有许许多多的开发者提供了应用开源项 目,贡献出他们的智慧和创造力.学习开源代码是掌握技术的 ...
- 【转】10款GitHub上最火爆的国产开源项目
将开源做到极致,提高效率方便更多用户 接触开源时间虽然比较短但是后续会努力为开源社区贡献自己微薄的力量 衡量一个开源产品好不好,看看产品在 GitHub 的 Star 数量就知道了.由此可见,GitH ...
- 【伯乐在线】最值得阅读学习的 10 个 C 语言开源项目代码
原文出处: 平凡之路的博客 欢迎分享原创到伯乐头条 伯乐在线注:『阅读优秀代码是提高开发人员修为的一种捷径』http://t.cn/S4RGEz .之前@伯乐头条 曾发过一条微博:『C 语言进阶有 ...
随机推荐
- python ---升级所有安装过的package
# -*- coding:utf8 -*- import pip from subprocess import call from pip._internal.utils.misc import ge ...
- kubernetes-dashboard登录出现forbidden 403
登录k8s dashboard https://xxxxx:6443/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard ...
- 解决本地Bootstrap字体图标不可见的问题
原文:https://www.jianshu.com/p/70ac459d33e7 作为Bootstrap的初学者,我最近遇到了一个问题:在使用Bootstrap字体图标时,图标不可见.使用代码如下: ...
- 网页调用文件另存为js
查看引用是否正常,页面添加html代码. <a id="downLoad" onclick="oDownLoad('downLoad')">下载&l ...
- 利用onMouseOver和onMouseOut实现图像翻滚
代码: <img src="images/001.jpg" alt="pic" onmouseover="this.src='images/00 ...
- Bootstrap-实现简单的网站首页
html: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset=" ...
- oracle 如何预估将要创建的索引的大小
一.1 oracle 如何预估将要创建的索引的大小 oracle 提供了2种可以预估将要创建的索引大小的办法: ① 利用包 Dbms_space.create_index_cost 直接得到 ② ...
- synchronized底层实现原理
基于进入和退出管程(Monitor)对象实现,无论显式(Monitorenter Monitorexit)还是隐式都是如此.同步方法并不是由monitorenter和monitorexit ...
- session有效期设置的两种方式
/**session有效期设置的两种方式: * 1.代码设置:session.setMaxInactiveInterval(30);//单位:秒.30秒有效期,默认30分钟. * 2.web.xml中 ...
- python笔记--------一
作用域: 每个变量或函数都有自己的作用域. 每个函数都定义了一个命名空间,也称为作用域. 在最顶层有一个符号表会跟踪这一层所有的名称定义和和他们当前的绑定. 调用函数时,会建立一个新的符号表(常称为栈 ...