using System.Data;
using System.IO;
using System.Text; namespace YanZhiwei.DotNet2.Utilities.Common
{
/// <summary>
/// CSV文件转换类
/// </summary>
public static class CSVHelper
{
#region 导出到csv文件
/// <summary>
/// 导出到csv文件
/// eg:
/// CSVHelper.ToCSV(_personInfoView, @"C:\Users\YanZh_000\Downloads\person.csv", "用户信息表", "名称,年龄");
/// </summary>
/// <param name="table">DataTable</param>
/// <param name="filePath">导出路径</param>
/// <param name="tableheader">标题</param>
/// <param name="columname">列名称,以','英文逗号分隔</param>
/// <returns>是否导出成功</returns>
public static bool ToCSV(this DataTable table, string filePath, string tableheader, string columname)
{
try
{
if (File.Exists(filePath))
File.Delete(filePath);
using (FileStream _stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
StreamWriter _writer = new StreamWriter(_stream, Encoding.UTF8);
_writer.WriteLine(tableheader);
_writer.WriteLine(columname);
for (int i = ; i < table.Rows.Count; i++)
{
for (int j = ; j < table.Columns.Count; j++)
{
_writer.Write(table.Rows[i][j].ToString());
_writer.Write(",");
}
_writer.WriteLine();
}
_writer.Close();
return true;
}
}
catch
{
return false;
}
}
#endregion
#region 将CSV文件导入到DataTable
/// <summary>
/// 将CSV文件导入到DataTable
/// </summary>
/// <param name="table">DataTable</param>
/// <param name="filePath">csv文件物理路径</param>
/// <param name="startRowIndex">数据导入起始行号</param>
/// <returns>DataTable</returns>
public static DataTable ImportToTable(this DataTable table, string filePath, int startRowIndex)
{
using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8, false))
{
int j = ;
while (reader.Peek() > -)
{
j = j + ;
string _line = reader.ReadLine();
if (j >= startRowIndex + )
{
string[] _dataArray = _line.Split(',');
DataRow _dataRow = table.NewRow();
for (int k = ; k < table.Columns.Count; k++)
{
_dataRow[k] = _dataArray[k];
}
table.Rows.Add(_dataRow);
}
}
return table;
}
}
#endregion
}
}

CSVHelper

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data;
using YanZhiwei.DotNet2.UtilitiesTests;
namespace YanZhiwei.DotNet2.Utilities.Common.Tests
{
[TestClass()]
public class CSVHelperTests
{
private DataTable TestTable;
[TestMethod()]
public void ToCSVTest()
{
for (Int16 i = ; i < ; i++)
{
DataRow _person = TestTable.NewRow();
_person["Name"] = "YanZhiwei" + i;
_person["Age"] = i;
TestTable.Rows.Add(_person);
}
bool _expected = true;
bool _actual = CSVHelper.ToCSV(TestTable, @"C:\Users\YanZh_000\Downloads\person.csv", "用户信息表", "名称,年龄");
Assert.AreEqual(_expected, _actual);
}
[TestInitialize]
public void InitTestTable()
{
TestTable = new DataTable();
TestTable.Columns.Add(new DataColumn("Name", typeof(string)));
TestTable.Columns.Add(new DataColumn("Age", typeof(int)));
} [TestMethod()]
public void ImportToTableTest()
{
DataTable _personInfoView = TestTable.Clone();
DataTable _expected = TestTable.Clone();
for (Int16 i = ; i < ; i++)
{
DataRow _person = _expected.NewRow();
_person["Name"] = "YanZhiwei" + i;
_person["Age"] = i;
_expected.Rows.Add(_person);
}
DataTable _actual = CSVHelper.ImportToTable(_personInfoView, @"C:\Users\YanZh_000\Downloads\person.csv", );
Assert.IsTrue(ResultSetComparer.AreIdenticalResultSets(_expected, _actual));
}
[TestCleanup]
public void ResetTable()
{
TestTable = null;
}
}
}

测试代码

using System.Data;
using System.IO; namespace DotNet.Utilities
{
/// <summary>
/// CSV文件转换类
/// </summary>
public static class CsvHelper
{
/// <summary>
/// 导出报表为Csv
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="strFilePath">物理路径</param>
/// <param name="tableheader">表头</param>
/// <param name="columname">字段标题,逗号分隔</param>
public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
{
try
{
string strBufferLine = "";
StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
strmWriterObj.WriteLine(tableheader);
strmWriterObj.WriteLine(columname);
for (int i = ; i < dt.Rows.Count; i++)
{
strBufferLine = "";
for (int j = ; j < dt.Columns.Count; j++)
{
if (j > )
strBufferLine += ",";
strBufferLine += dt.Rows[j].ToString();
}
strmWriterObj.WriteLine(strBufferLine);
}
strmWriterObj.Close();
return true;
}
catch
{
return false;
}
} /// <summary>
/// 将Csv读入DataTable
/// </summary>
/// <param name="filePath">csv文件路径</param>
/// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
public static DataTable csv2dt(string filePath, int n, DataTable dt)
{
StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
int i = , m = ;
reader.Peek();
while (reader.Peek() > )
{
m = m + ;
string str = reader.ReadLine();
if (m >= n + )
{
string[] split = str.Split(','); System.Data.DataRow dr = dt.NewRow();
for (i = ; i < split.Length; i++)
{
dr = split;
}
dt.Rows.Add(dr);
}
}
return dt;
}
}
}

C#关于CSV文件的导入和导出以及转化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Data;
using DEV_JIZHANG.Models; namespace DEV_JIZHANG.Common
{
public class CSVHelp
{ public char[] chSplit = new char[] { '|' };
#region public function
public DataTable ImportCSVToDataTable(
string RecoveryPath,
ref string err)
{
int intColCount = ;
bool blnFlag = true;
DataTable mydt = new DataTable("myTableName");
DataColumn mydc;
DataRow mydr;
//string strpath = "test.wxt";
string strline;
string[] aryline; try
{
System.IO.StreamReader mysr = new System.IO.StreamReader(RecoveryPath);
while ((strline = mysr.ReadLine()) != null)
{
aryline = strline.Split(chSplit);
if (blnFlag)
{
blnFlag = false;
intColCount = aryline.Length;
for (int i = ; i < aryline.Length; i++)
{
mydc = new DataColumn(aryline[i]);
mydc.ColumnName = i.ToString();
mydt.Columns.Add(mydc);
}
}
mydr = mydt.NewRow();
for (int i = ; i < intColCount; i++)
{
mydr[i] = aryline[i];
}
mydt.Rows.Add(mydr);
} return mydt;
}
catch (Exception ex)
{
err = ex.ToString();
return null;
} //dgData.DataSource =mydt;
//dgData.DataBind();
} public void DataTableToCSVFile(
System.Data.DataTable dt,
string BackupPath,
string strSplitChar,
ref string err)
{ string row;
try
{
//string header;
string tmp;
//StreamReader sr = new StreamReader(xbkPath);
//header = sr.ReadLine();
//sr.Close();
FileStream fs = File.Create(BackupPath);
StreamWriter sw = new StreamWriter(fs);
//sw.WriteLine(header); foreach (DataRow dr in dt.Rows)
{
row = "";
for (int i = ; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - )
{
tmp = dr[i].ToString().Trim().Replace(strSplitChar, "");
row = row + tmp + strSplitChar;
}
else
{
tmp = dr[i].ToString().Trim().Replace(strSplitChar, "");
row = row + tmp;
}
}
sw.WriteLine(row); }
sw.Flush();
sw.Close();
}
catch (Exception ex)
{
err = ex.ToString();
}
} //默认密钥向量
public byte[] Keys = { 0xEF, 0xAB, 0x56, 0x73, 0x90, 0x32, 0xCD, 0x12 };
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public string EncryptDES(string encryptString, string encryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch
{
return encryptString;
}
}
#endregion
}
}

CSVHelper

https://github.com/JoshClose/CsvHelper

C# csv 操作类的更多相关文章

  1. C#操作CSV存取类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  2. java csv 文件 操作类

    一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...

  3. csv操作帮助类

    功能描述: 集合转换为csv数据 DataSe转换为csv数据 using System; using System.Collections.Generic; using System.Data; u ...

  4. Excel 操作类

    转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...

  5. C# 文件操作类大全

      C# 文件操作类大全 时间:2015-01-31 16:04:20      阅读:1724      评论:0      收藏:0      [点我收藏+] 标签: 1.创建文件夹 //usin ...

  6. 【知识必备】ezSQL,最好用的数据库操作类,让php操作sql更简单~

    最近用php做了点小东东,用上了ezSQL,感觉真的很ez,所以拿来跟大家分享一下~ ezSQL是一个非常好用的PHP数据库操作类.著名的开源博客WordPress的数据库操作就使用了ezSQL的My ...

  7. JQuery操作类数组的工具方法

    JQuery学习之操作类数组的工具方法 在很多时候,JQuery的$()函数都返回一个类似数据的JQuery对象,例如$('div')将返回div里面的所有div元素包装的JQuery对象.在这中情况 ...

  8. Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)

    今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...

  9. Util应用程序框架公共操作类(九):Lambda表达式扩展

    上一篇对Lambda表达式公共操作类进行了一些增强,本篇使用扩展方法对Lambda表达式进行扩展. 修改Util项目的Extensions.Expression.cs文件,代码如下. using Sy ...

随机推荐

  1. shell脚本编程-循环(for、while、until)

    for命令格式:– list参数:迭代中要用的一系列值– 每个迭代中,变量var会包含列表中的当前值– do和done语句之间输入的命令可以是一条或多条标准的bash shell命令   1 2 3 ...

  2. 快速理解Docker - 容器级虚拟化解决方案

    是什么 简单的说Docker是一个构建在LXC之上的,基于进程容器(Processcontainer)的轻量级VM解决方案 拿现实世界中货物的运输作类比, 为了解决各种型号规格尺寸的货物在各种运输工具 ...

  3. 01 viewport

    <meta name="viewport" content="width=device-width,initial-scale=1.0">

  4. markdown语法集锦

    参考:http://wowubuntu.com/markdown/#blockquote 1. 标题 # 一级标题 ## 二级标题 ### 三级标题 共六级标题 2. 列表 有序列表:1,2,3: 无 ...

  5. iOS 本地加载html登陆页面

    Html的代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  6. JSON Web Token

    What is JSON Web Token? JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact a ...

  7. MySql避免重复插入记录方法(ignore,Replace,ON DUPLICATE KEY UPDATE)

    ON DUPLICATE KEY UPDATE  博客 http://blog.csdn.net/jbboy/article/details/46828917

  8. Oracle 10G如何从recovery catalog中Unregister目标数据库

    从10g开始,RMAN简化了unregister目标数据库的步骤 方法1: $rman target system/oracle@test catalog rman/rman@catadb rman& ...

  9. PL/SQL Developer连接到Oracle 12c

    安装32位的Oracle客户端instantclient-basic-nt-12.1.0.1.0.zip 下载地址:http://www.oracle.com/technetwork/topics/w ...

  10. Python:安装mssql模块功能,并实现与sqlserver连接、查询

    由于我系统是x64系统,所以下载python2.7 x64.下载地址:https://www.python.org/downloads/release/python-2712/, 经过测试发现这个版本 ...