using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
class CsvHelp
{
public DataTable CSV2DataTable(string fileName)
{
try
{
DataTable dt = new DataTable();
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
aryLine = strLine.Replace('"', ' ').Replace(" ", "").TrimEnd(',').Split(',');
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i]);
try
{
dt.Columns.Add(dc);
}
catch (Exception ex)
{
DbHelp.Error = ex.ToString();
return null;
}
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}
sr.Close();
fs.Close();
return dt;
}
catch (Exception)
{
return null;
}
}
public void DataTable2CSV(DataTable dt, string AbosultedFilePath)
{
//MessageBox.Show(AbosultedFilePath);
FileStream fs = new FileStream(AbosultedFilePath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, new UnicodeEncoding());
//Tabel header
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName);
sw.Write("\t");
}
sw.WriteLine("");
//Table body
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sw.Write(DelQuota(dt.Rows[i][j].ToString()));
sw.Write("\t");
}
sw.WriteLine("");
}
sw.Flush();
sw.Close();
}
public string DelQuota(string str)
{
string result = str;
string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
for (int i = 0; i < strQuota.Length; i++)
{
if (result.IndexOf(strQuota[i]) > -1)
result = result.Replace(strQuota[i], "");
}
return result;
}
}
使用方法
//读取文件内容
CsvHelp ch = new CsvHelp();
DataTable dt = ch.CSV2DataTable(FileRes + "/" + FileName.ToString());
if (dt == null)
{
showMessage(DbHelp.Error, true);
return;
}