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