开源项目 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 语言进阶有 ...
随机推荐
- javaweb之添加学生信息
1登录账号:要求由6到12位字母.数字.下划线组成,只有字母可以开头:(1分) 2登录密码:要求显示“• ”或“*”表示输入位数,密码要求八位以上字母.数字组成.(1分) 3性别:要求用单选框或下拉框 ...
- 四种方法获取可执行程序的文件路径(.NET Core / .NET Framework)
原文:四种方法获取可执行程序的文件路径(.NET Core / .NET Framework) 本文介绍四种不同的获取可执行程序文件路径的方法.适用于 .NET Core 以及 .NET Framew ...
- SQL Server——死锁查看
一.通过语句查看 --查询哪些死锁SELECT request_session_id spid, OBJECT_NAME( resource_associated_entity_id ) tableN ...
- java之mybatis之模糊查询
1.在 mybatis 中,模糊查询可以有以下方式 (1).第一种,直接将封装好的条件传给 sql 语句 <select id="findByName" parameterT ...
- txt文件每行内容与图片文件名字组合,输出txt格式
import os dir_list = os.listdir('C:\\Users\\10107472\\Desktop\\practice\\JPEGImages')i=0f1=open('C:\ ...
- Vue项目开发相关问题总结
Vue项目开发相关问题总结 一.创建一个项目(两种方式) 1.通过CLI命令行创建,具体步骤如下: (1)Node 版本要求 Vue CLI 需要 Node.js 8.9 或更高版本 (推荐 8.11 ...
- MongoDB 基本概念
MongoDB和关系型数据库的对应关系 关系数据库 MongoDB 数据库 database 数据库 database 表格 table 集合 collection 行 row 文档 ...
- WC_Project
个人项目:WC_Project 一.GitHub项目地址 GitHub项目地址:https://github.com/ting9500/WC_GNIT.git 二.PSP表格 PSP2.1 Perso ...
- 26.centos7基础学习与积累-012-文件和目录的属性
从头开始积累centos7系统运用 大牛博客:https://blog.51cto.com/yangrong/p5 1.文件的属性(文件的信息描述): [root@python01 ~]# ls -l ...
- 优化nginx数据包头缓存
例子:414错误,网址太长. 长网址访问例子: 以下脚本会生成一个长网址并访问,导致414长网址报错. [root@proxy ~]#vim nginx_test.sh #!/bin/bash URL ...