using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
public class CSVUtil
{
public CSVUtil()
{
}
//write a new file, existed file will be overwritten
public static void WriteCSV(string filePathName,List<String[]>ls)
{
WriteCSV(filePathName,false,ls);
}
//write a file, existed file will be overwritten if append = false
public static void WriteCSV(string filePathName,bool append, List<String[]> ls)
{
StreamWriter fileWriter=new StreamWriter(filePathName,append,Encoding.Default);
foreach(String[] strArr in ls)
{
fileWriter.WriteLine(String.Join(",",strArr));
}
fileWriter.Flush();
fileWriter.Close();
}
public static List<String[]> ReadCSV(string filePathName)
{
try
{
List<String[]> ls = new List<String[]>();
StreamReader fileReader = new StreamReader(filePathName);
if (fileReader == null)
{
throw new Exception("The file is not exit!");
}
string strLine = "";
string str = ",(?=\")|(?<=\"),";
Regex r = new Regex(str);
//string[] strSplit = {",\"","\","};
strLine = fileReader.ReadLine(); //first line:header, do not need
if (strLine == null)
{
throw new Exception("The file is null!");
}
while (strLine != null)
{
if (strLine.Contains("\""))
{
if (strLine != null && strLine.Length > 0)
{
if (r.IsMatch(strLine))
{
string[] temp = { };
temp = r.Split(strLine);
List<string> list = new List<string>();
//temp = strLine.Split(strSplit, StringSplitOptions.None);
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].StartsWith("\"") && temp[i].EndsWith("\""))
{
temp[i] = temp[i].Substring(1, temp[i].Length - 2);
list.Add(temp[i]);
}
else
{
string[] ttemp = temp[i].Split(',');
for (int j = 0; j < ttemp.Length; j++)
list.Add(ttemp[j]);
}
}
ls.Add(list.ToArray());
}
else
ls.Add(strLine.Split(','));
}
}
else
{
if (strLine != null && strLine.Length > 0)
{
ls.Add(strLine.Split(','));
}
}
strLine = fileReader.ReadLine();
}
fileReader.Close();
return ls;
}
catch(Exception ex)
{
return null;
}
}
}
分享到:
相关推荐
本文实例讲述了C#读取csv格式文件的方法。分享给大家供大家参考。具体实现方法如下: 一、CSV文件规则 1 开头是不留空,以行为单位。 2 可含或不含列名,含列名则居文件第一行。 3 一行数据不跨行,无空行。 4 以...
使用C#读取csv文件的实例源码_0520.rar
最好用的读取csv文件代码,可以读取csv和EXCLE的文件
C#读取csv文件,可以设置表头起始行跟正文起始行(为了某些特殊需求)。 读取csv生成一个datatable类返回。 缺点(“单元格”不支持换行)。
C#读取CSV EXCEL文件,比较好用
C#读取csv文件的实例源码
使用C#读取csv文件的实例源码
使用C#读取csv文件的实例源码201902
使用C#读取csv文件的实例源码【201903】
使用C#读取csv文件的实例源码(0515).rar
使用C#读取csv文件的实例源码.rar.
运行环境:vs2010 Csv文件的读写,操作Csv文件,将dataGridView导出到CSV,加载CSV数据到DataGridView,包含对逗号的处理,内容中包含逗号也可以
使用C#读取csv文件的实例源码.rar
C#解析csv,解决中文编码的一个代码例子
使用C#读取csv文件的实例源码2019
使用C#读取csv文件的实例源码201903
C# 读取和写入EXCELcsv表格 获取指定行的内容 C#+VB源码