C# csv 操作类
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 操作类的更多相关文章
- C#操作CSV存取类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...
- java csv 文件 操作类
一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...
- csv操作帮助类
功能描述: 集合转换为csv数据 DataSe转换为csv数据 using System; using System.Collections.Generic; using System.Data; u ...
- Excel 操作类
转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...
- C# 文件操作类大全
C# 文件操作类大全 时间:2015-01-31 16:04:20 阅读:1724 评论:0 收藏:0 [点我收藏+] 标签: 1.创建文件夹 //usin ...
- 【知识必备】ezSQL,最好用的数据库操作类,让php操作sql更简单~
最近用php做了点小东东,用上了ezSQL,感觉真的很ez,所以拿来跟大家分享一下~ ezSQL是一个非常好用的PHP数据库操作类.著名的开源博客WordPress的数据库操作就使用了ezSQL的My ...
- JQuery操作类数组的工具方法
JQuery学习之操作类数组的工具方法 在很多时候,JQuery的$()函数都返回一个类似数据的JQuery对象,例如$('div')将返回div里面的所有div元素包装的JQuery对象.在这中情况 ...
- Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)
今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...
- Util应用程序框架公共操作类(九):Lambda表达式扩展
上一篇对Lambda表达式公共操作类进行了一些增强,本篇使用扩展方法对Lambda表达式进行扩展. 修改Util项目的Extensions.Expression.cs文件,代码如下. using Sy ...
随机推荐
- Android 关于ListView中adapter调用notifyDataSetChanged无效的原因
话说这个问题已经困扰我很久了,一直找不到原因,我以为只要数据变了,调用adapter的notifyDataSetChanged就会更新列表,最近在做微博帐号管理这一块,想着动态更新列表,数据是变了,但 ...
- 关于C、OC、C++、OC++、Swift的一些常识
关于C.OC.C++.OC++.Swift的一些常识 OC是C语言的一个超集,是一门面向对象的语言,因为苹果的崛起而火,API主要是cocoa(OSX)和cocoatouch(iOS),GCC 和 C ...
- box2dweb基础
简介 大名鼎鼎的物理引擎box2d基本上大家都听说过,网上有两个javascript版本的box2d库,一个时box2djs,已经停止维护,一个是box2dweb.下面就来介绍一下box2dweb的基 ...
- linux:lnmp环境搭建
一.准备工作(把安装环境需要使用到的包都下载好) mysql(官网):http://dev.mysql.com/downloads/ php(官网):http://php.net/downloads. ...
- HTML语言的一些元素(一)
1)标题的六个等级:<h1>,<h2>,<h3>,<h4>,<h5>,<h6>.如果写了诸如:<h7>等,则作为正文 ...
- typedef NS_OPTIONS 位移的枚举
typedef NS_OPTIONS里面的枚举可以并存使用 用 | 来并存
- M面经Prepare: Delete Words Starting With One Character
给定一个char array, 这个array是一个句子,然后给定一个字母,把这个array里面带有这个字母开头的单次删掉,操作是要求in place. 检测 array[i]==' ' & ...
- Leetcode: String to Integer
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 搭建企业cacti服务器
搭建企业cacti服务器 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 今天搭建了cacti,为了方便监控我的交换机~因为查了很多zabbix的资料关于监控交换机的教程~我都屡屡失 ...
- Shiro--权限控制
来自: http://m.oschina.net/blog/92003 1.applicationContext-shiro.xml配置:实现认证和授权 <!-- shiro start --& ...