c# 简单文件流读写CSV文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Reflection;
using System.IO;
using System.Data;
using System.Web;
using System.Data.Odbc;
using System.Text.RegularExpressions;
using System.Collections; namespace KernelClass
{
public class CSVHelper
{ /// <summary>
/// The class CSVHelper read the data from CSV file and store it in a DataTable class,
/// and allows to return a column with index or column name.
/// </summary>
private static readonly char[] FormatSplit = new char[] { ',' };
private const string replaceDoubleQuotes = "$replaceDoubleQuotes$";
private const string tableName = "csvTable"; public static DataTable ReadCSV(string filePath)
{
FileInfo fi = new FileInfo(filePath);
if (fi == null || !fi.Exists) return null; StreamReader reader = new StreamReader(filePath); string line = string.Empty;
int lineNumber = ; DataTable dt = new DataTable(); while ((line = reader.ReadLine()) != null)
{
if (lineNumber == )
{
dt = CreateDataTable(line);
if (dt.Columns.Count == ) return null;
}
else
{
bool isSuccess = CreateDataRow(ref dt, line);
if (!isSuccess)
{
throw new FileLoadException("There are some data unconsistent in your file.");
}
}
lineNumber++;
}
reader.Close(); //如果最后一列是空的话就删除
bool HasValueForLastestColumn = false;
int indexLastestColumn = dt.Columns.Count -;
for (var i = ; i < dt.Rows.Count; i++)
{
if (!string.IsNullOrEmpty(dt.Rows[indexLastestColumn][i].ToString().Trim())) {
HasValueForLastestColumn = true;
break;
}
}
if (HasValueForLastestColumn) {
dt.Columns.RemoveAt(indexLastestColumn);
}
return dt;
} public static bool WriteCSV(DataTable _dataSourc, string filePath)
{
string data = ExportCSV(_dataSourc);
return PhysicalFile.SaveFile(data, filePath);
} public static string ExportCSV(DataTable _dataSource)
{
StringBuilder strbData = new StringBuilder();
foreach (DataColumn column in _dataSource.Columns)
{
strbData.Append(column.ColumnName + ",");
}
strbData.Append("\n");
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = ; i < _dataSource.Columns.Count; i++)
{
string rowValue = dr[i].ToString().Replace("\"", "\"\"");
if(rowValue.Contains(','))
strbData.Append("\"" + dr[i].ToString().Replace("\"", "\"\"") + "\",");
else
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
} public static List<double> GetColumnWithName(string columnName, DataTable dt)
{
List<double> list = new List<double>(); var index = dt.Columns.IndexOf(columnName);
list = GetColumnWithIndex(index, dt); return list;
} public static List<double> GetColumnWithIndex(int index, DataTable dt)
{
List<double> list = new List<double>(); foreach (DataRow dr in dt.Rows)
{
var s = dr[index].ToString();
if (string.Compare(s, "") == )
{
break;
}
double value = Convert.ToDouble(s);
list.Add(value);
} return list;
} private static DataTable CreateDataTable(string line)
{
DataTable dt = new DataTable();
foreach (string field in
line.Split(FormatSplit, StringSplitOptions.None))
{
dt.Columns.Add(field);
}
return dt;
} private static bool CreateDataRow(ref DataTable dt, string line)
{
DataRow dr = dt.NewRow();
string src = string.Empty;
Hashtable fields = new Hashtable(); if (!string.IsNullOrEmpty(line))
{
src = line.Replace("\"\"", replaceDoubleQuotes);
//正则表达式找出用双引号包括的字符串, 下面循环是为了防止字符串中含有分隔符 ,
MatchCollection col = Regex.Matches(src, "\"([^\"]+)\"", RegexOptions.ExplicitCapture);
IEnumerator ie = col.GetEnumerator(); while (ie.MoveNext())
{
string patn = ie.Current.ToString();
int key = src.Substring(, src.IndexOf(patn)).Split(',').Length-; if (!fields.ContainsKey(key))
{
fields.Add(key, patn.Trim(new char[] { ',', '"' }));
src = src.Replace(patn, "");
}
} string[] arr = src.Split(',');
for (int i = ; i < arr.Length; i++)
{
if (!fields.ContainsKey(i))
fields.Add(i, arr[i]);
}
} if (fields.Count == || fields.Count > dt.Columns.Count)
{
return false;
} for (int i = ; i < fields.Count; i++)
{
dr[i] = fields[i].ToString().Replace(replaceDoubleQuotes, "\"");
} dt.Rows.Add(dr);
return true;
}
} }
c# 简单文件流读写CSV文件的更多相关文章
- js实现使用文件流下载csv文件
1. 理解Blob对象 在Blob对象出现之前,在javascript中一直没有比较好的方式处理二进制文件,自从有了Blob了,我们就可以使用它操作二进制数据了.现在我们开始来理解下Bolb对象及它的 ...
- 使用commons-csv简单读写CSV文件
文章首发于我的github博客 需求 客户的开发测试环境将做迁移.因此需要对zookeeper上的重要的数据以CSV文件格式做备份. 本文通过Apache的commons-csv操作CSV文件.官网地 ...
- 用opencsv文件读写CSV文件
首先明白csv文件长啥样儿: 用excel打开就变成表格了,看不到细节 推荐用其它简单粗暴一点儿的编辑器,比如Notepad++, csv文件内容如下: csv文件默认用逗号分隔各列. 有了基础的了解 ...
- 使用Python读写csv文件的三种方法
Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是 ...
- python3读写csv文件
python读取CSV文件 python中有一个读写csv文件的包,直接import csv即可.利用这个python包可以很方便对csv文件进行操作,一些简单的用法如下. 1. 读文件 csv_ ...
- python读写csv文件
文章链接:https://www.cnblogs.com/cloud-ken/p/8432999.html Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗 ...
- 【基础巩固】文件流读写、大文件移动 FileStream StreamWriter File Path Directory/ ,m资料管理器(递归)
C#获取文件名 扩展名 string fullPath = @"d:\test\default.avi"; string filename = Path.GetFileName(f ...
- JAVA读写CSV文件
最近工作需要,需要读写CSV文件的数据,简单封装了一下 依赖读写CSV文件只需引用`javacsv`这个依赖就可以了 <dependency> <groupId>net.sou ...
- (Python基础教程之十二)Python读写CSV文件
Python基础教程 在SublimeEditor中配置Python环境 Python代码中添加注释 Python中的变量的使用 Python中的数据类型 Python中的关键字 Python字符串操 ...
随机推荐
- android使用library工程问题
在windows系统下,library project必须和project处于相同的盘符中,因为如果在不同盘符,project.properties中的android.library.referenc ...
- WCF中使用控件的委托,线程中的UI委托
UI界面: <Window x:Class="InheritDemo.Window1" xmlns="http://schemas.microsoft.com/wi ...
- 包(package) 与 导入(import) 语句剖析
A) 包(package):用于将完成不同功能的类分门别类,放在不同的目录下. B)命名规则:将公司域名翻转作为包名.例如www.vmaxtam.com域名,那么包名就是com.vmaxtam 每个字 ...
- 苏泊尔借助微软CRM提升客户满意度
企业背景 作为中国最大.全球第二的炊具研发制造商和中国小家电领先品牌,品质和创新一是苏泊尔矢志追求的企业理念,从火红点无油烟锅的发明到能做柴火饭的球釜IH饭煲的面世,苏泊尔用产品的创新和品质的承诺,不 ...
- linux kernel 0.11 head
head的作用 注意:bootsect和setup汇编采用intel的汇编风格,而在head中,此时已经进入32位保护模式,汇编的采用的AT&T的汇编语言,编译器当然也就变成对应的编译和连接器 ...
- chkconfig 命令详解
chkconfig命令主要用来更新(启动或停止)和查询系统服务的运行级信息.谨记chkconfig不是立即自动禁止或激活一个服务,它只是简单的改变了符号连接. 使用语法: chkconfig [--a ...
- centos6.4 安装 hive 0.12.0
环境:centos6.4 64bit, 前提:hadoop已经正常运行,可以使用hadoop dfsadmin -report查看 hive 解压 tar zcvf hive-0.12.0.ta ...
- 用cmd命令合并N个文件
今天早上朋友发我一篇小说(42个TXT文件),让我给他合并为一个文件.我首先想到的是“Copy”命令,它可以复制文件,也可以合并文件. 例如:合并1.txt和2.txt到12.txt(其为ASCII文 ...
- 微软职位内部推荐-Sr SDE
微软近期Open的职位: MSN reaches nearly half a billion people across the globe where we are the #1 portal in ...
- comparing-html5-mobile-ui-frameworks
http://html5hub.com/comparing-html5-mobile-ui-frameworks/