public class CSVFileHelper
{
/// <summary>
/// 将DataTable中数据写入到CSV文件中
/// </summary>
/// <param name="dt">提供保存数据的DataTable</param>
/// <param name="fileName">CSV的文件路径</param>
public static void SaveCSV(DataTable dt, string fullPath)
{
FileInfo fi = new FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
string data = "";
//写出列名称
for (int i = ; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - )
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = ; i < dt.Rows.Count; i++)
{
data = "";
for (int j = ; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.Format("\"{0}\"", str);
} data += str;
if (j < dt.Columns.Count - )
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
DialogResult result = MessageBox.Show("CSV文件保存成功!");
if (result == DialogResult.OK)
{
System.Diagnostics.Process.Start("explorer.exe", Common.PATH_LANG);
}
} /// <summary>
/// 将CSV文件的数据读取到DataTable中
/// </summary>
/// <param name="fileName">CSV文件路径</param>
/// <returns>返回读取了CSV数据的DataTable</returns>
public static DataTable OpenCSV(string filePath)
{
Encoding encoding = Common.GetType(filePath); //Encoding.ASCII;//
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); //StreamReader sr = new StreamReader(fs, Encoding.UTF8);
StreamReader sr = new StreamReader(fs, encoding);
//string fileContent = sr.ReadToEnd();
//encoding = sr.CurrentEncoding;
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine = null;
string[] tableHead = null;
//标示列数
int columnCount = ;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
//strLine = Common.ConvertStringUTF8(strLine, encoding);
//strLine = Common.ConvertStringUTF8(strLine); if (IsFirst == true)
{
tableHead = strLine.Split(',');
IsFirst = false;
columnCount = tableHead.Length;
//创建列
for (int i = ; i < columnCount; i++)
{
DataColumn dc = new DataColumn(tableHead[i]);
dt.Columns.Add(dc);
}
}
else
{
aryLine = strLine.Split(',');
DataRow dr = dt.NewRow();
for (int j = ; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}
if (aryLine != null && aryLine.Length > )
{
dt.DefaultView.Sort = tableHead[] + " " + "asc";
} sr.Close();
fs.Close();
return dt;
}
}

http://www.cnblogs.com/Clin/archive/2013/03/14/2959022.html

C#读取CSV的更多相关文章

  1. sparkR读取csv文件

    sparkR读取csv文件 The general method for creating SparkDataFrames from data sources is read.df. This met ...

  2. C# 读取 CSV 文件

    最近做一个C#项目要导入CSV文件中的数据到Oracle中,使用Aspose.Cells读取中文字段标题却乱码,表的最后多出几行null记录,而且不是免费的,后来找到了NPOI,顾名思义,就是POI的 ...

  3. PHP读取CSV数据写入数据库

    /*读取csv文件*/ public function testCsv(){ $fileName = "tel.csv"; $fp=fopen($fileName,"r& ...

  4. VB6.0 读取CSV文件

    最近做了一个Upload文件的需求,文件的格式为CSV,读取文件的方法整理了一下,如下: 1.先写了一个读取CSV文件的Function: '读取CSV文件 '假设传入的参数strFile=C:\Do ...

  5. php读取csv文件,在linux上出现中文读取不到的情况 解决方法

    今,php读取csv文件,在linux上出现中文读取不到的情况,google,后找到解决办法<?phpsetlocale(LC_ALL, 'zh_CN');$row = 1;$handle = ...

  6. 内容写到 csv 格式的文件中 及 读取 csv 格式的文件内容

    <?php/*把内容写到 csv 格式的文件中 基本思路是:1.用 $fp = fopen("filename", 'mode')打开一个csv文件,可以是打开时才建立的2. ...

  7. Unity 读取CSV与Excel

    前几天看到我们在游戏中需要动态加载某些角色的游戏策划值,关于这个问题怎么解决呢?其实办法很多种,归根到底,就是数据的读取.我们可以想到的存储数据的载体有很多.例如:txt,xml,csv,excel. ...

  8. 使用univocity-parsers创建和读取csv文件

    import com.univocity.parsers.csv.CsvFormat;import com.univocity.parsers.csv.CsvParser;import com.uni ...

  9. PHP读取CSV大文件导入数据库的示例

    对于数百万条数据量的CSV文件,文件大小可能达到数百M,如果简单读取的话很可能出现超时或者卡死的现象. 为了成功将CSV文件里的数据导入数据库,分批处理是非常必要的. 下面这个函数是读取CSV文件中指 ...

  10. Python 读取csv文件到excel

    朋友问我如何通过python把csv格式的文件另存为xls文件,自己想了想通过读取csv文件然后再保存到xls文件中即可,也许还有其他简单的方法,但这里也为了练习python语法及其他知识,所以采用了 ...

随机推荐

  1. 005.Docker存储管理

    一 Docker volume形态 因为Docker 采用 AFUS 分层文件系统时,文件系统的改动都是发生在最上面的容器层,在容器的生命周期内,它是持续的,包括容器在被停止后.但是,当容器被删除后, ...

  2. JAVA编程:字符串转为数字求和

    程序从命令行接入数字,求和,如果接入的是字符串的解决办法 设计思想: 首先定义一个double类型的一维数组,然后在定义一个double型的变量sum,并赋值为0,用if循环判断从命令行是否有参数输入 ...

  3. Codeforces.788C.The Great Mixing(bitset DP / BFS)

    题目链接 \(Description\) 有k种饮料,浓度Ai给出,求用最少的体积配成n/1000浓度的饮料. \(Solution\) 根据题意有方程 (A1x1+A2x2+...+Anxn)/[( ...

  4. C++ 函数模板基础知识

    为什么要引入模板:为了避免代码重复,程序员可以编写脱离数据类型通用模板. 模板的分类:函数模板 + 类模板 注意:模板的声明或定义只能在全局,命名空间或类范围内进行.不能在函数内进行,比如不能在mai ...

  5. JSON数据之使用Fastjson进行解析(一)

    据说FastJson是目前最快的解析Json数据的库,而且是国人开发出来的开源库.顶一下,付上官方网址:http://code.alibabatech.com/wiki/pages/viewpage. ...

  6. C#利用QRCoder生产二维码

    系统使用.NET4.5.1 代码如下: using System; using System.Collections.Generic; using System.Linq; using System. ...

  7. CS模式,客户端页面加载

    public MainForm() { //1.初始化视图 InitializeComponent(); //2.加载程序 this.Load += new System.EventHandler(t ...

  8. C# System.Collections.ArrayList

    using System; using System.Collections; public class SamplesArrayList { public static void Main() { ...

  9. codeblocks技巧收集

    Ctrl+Shift+C  注释代码块 Ctrl+Shift+X  取消注释

  10. Seaslog安装和参数配置

    详细文档访问:https://github.com/Neeke/SeasLog/blob/master/README_zh.md 源码安装步骤: 1.先下载Seaslog源码,下载地址:http:// ...