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 一个漂亮的Android日期和时间选择器:DateTimePicker
DateTimePicker这个类库包含了漂亮的 DatePicker 和 TimePicker ,类似于在新 Google Agenda App中看到的. 项目主页:http://www.open- ...
- ios中常用数据类型相互转换
ios中常用数据类型相互转换 //1. NSMutableArray和NSArray互转 // NSArray转为NSMutableArray NSMutableArray *arrM = [arr ...
- ArcEngine和GDAL读写栅格数据机制对比(二)—— IPixelBlock读写栅格
以下是设定一个矩形框,用IPixelBlock将256*256瓦片tile拼接成一个整块影像的代码,row1, col1, row2, col2是一个矩形框行列号范围.level是瓦片的金字塔等级.这 ...
- 无法定位程序输入点 crtis tailoredApp 于动态链接库MSVCR110.dll
最近 在安装完 PHP开发,集成环境 WAMP 后,运行老是提示 “无法定位程序输入点 crtis tailoredApp 于动态链接库MSVCR110.dll” 网上百度,大多说是重新下载“ ...
- Spring AOP 问与答
AOP的实现有哪些 AOP常见的实现有: Spring AOP Aspectj Guice AOP Jboss AOP 等 AOP Alliance 是什么, 为什么Spring AOP, G UIC ...
- iOS UITableView的分割线短15像素,移动到最左边的方法(iOS8)
有好几个朋友问我ios 分割线端了一些 如何解决,于是我就写一篇博客吧.为什么我说是少了15像素呢?首先我们拖拽一个默认的tableview 控件! 看下xcode5 面板的inspector(检查器 ...
- 数据库调优过程(二):找到IO不存在问题,而是sqlserver单表写入IO瓶颈
物理机上测试IO是否为瓶颈: 使用一个死循环insert into测试数据库最大写入速度: use [iTest]; declare @index int; ; begin ; INSERT into ...
- tornado中使用Mako模版
tornado是一个优秀的python的开源web 框架,框架本身的性能确实很好,但是他自带的模版只能说是一般般.关于tornado的详细信息可以直接到管网参考. http://www.tornado ...
- devexpress13学习系列(三)PDFViewer(3)
PdfDocumentProperties Class 该类,用来显示载入的pdf文件的属性,包括: Name Description Application Indicates the appl ...
- Leetcode: Remove K Digits
Given a non-negative integer num represented as a string, remove k digits from the number so that th ...