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 ...
随机推荐
- Spring 3.x jar 包详解 与 依赖关系(转)
以下的内容我会持续更新(当然是我有新发现的时候); 以下内容是我在网上搜索.整理.修改的而成的内容.由于很多内容都是转载了,无法追溯到源头,因此无法一一对原作者进行道谢. 这几天,我查阅大量的官方的文 ...
- 史上最全的CSS样式整理
一 字体属性:(font) 大小 {font-size: x-large;}(特大) xx-small;(极小) 一般中文用不到,只要用数值就可以,单位:PX.PD 样式 {font-style: o ...
- jQuery基础修炼圣典—DOM篇(一)
一.DOM节点的创建 1.创建节点及节点属性 通过JavaScript可以很方便的获取DOM节点,从而进行一系列的DOM操作.但实际上一般开发者都习惯性的先定义好HTML结构,但这样就非常不灵活了. ...
- [ArcEngine]IFeatureBuffer使用
public static void LoadOnlyModeInsert(IFeatureClass featureClass, List < IGeometry > geometryL ...
- canvas的代码封装
(function(window,document){ var cs2d = function(selector,options){ return new cs2d.fn.init(selector, ...
- Java多线程实现
1.继承Thread类,由于Java单继承特性,此方法并不推荐. 2.实现Runnable接口,代码如下 class MyThread implements Runnable { private St ...
- iOS面试必看,最全梳理
序言 目前形势,参加到iOS队伍的人是越来越多,甚至已经到供过于求了.今年,找过工作人可能会更深刻地体会到今年的就业形势不容乐观,加之,培训机构一火车地向用人单位输送iOS开发人员,打破了生态圈的动态 ...
- Array.prototype.slice && Array.prototype.splice 用法阐述
目的 对于这两个数组操作接口,由于不理解, 往往被误用, 或者不知道如何使用.本文尝试给出容易理解的阐述. 数组 什么是数组? 数组是一个基本的数据结构, 是一个在内存中依照线性方式组织元素的方式, ...
- C#控件:TabControl
tabcontrol在切换页面的时候经常用到 这里讲下如何让tabcontrol更好看 ref:http://blog.csdn.net/conmajia/article/details/759671 ...
- linux下利用nginx部署python网站
首先目标机器需要安装python nginx uwsgi,其次,需要给Nginx写配置文件,大体内容如下,具体内容可见 http://blog.cn2p.com/web-server/nginx-uw ...