C# - CSV(Comma-Separated Values)文件读取.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text; namespace CsvFile
{
/// <summary>
/// Determines how empty lines are interpreted when reading CSV files.
/// These values do not affect empty lines that occur within quoted fields
/// or empty lines that appear at the end of the input file.
/// </summary>
public enum EmptyLineBehavior
{
/// <summary>
/// Empty lines are interpreted as a line with zero columns.
/// </summary>
NoColumns,
/// <summary>
/// Empty lines are interpreted as a line with a single empty column.
/// </summary>
EmptyColumn,
/// <summary>
/// Empty lines are skipped over as though they did not exist.
/// </summary>
Ignore,
/// <summary>
/// An empty line is interpreted as the end of the input file.
/// </summary>
EndOfFile,
} /// <summary>
/// Common base class for CSV reader and writer classes.
/// </summary>
public abstract class CsvFileCommon
{
/// <summary>
/// These are special characters in CSV files. If a column contains any
/// of these characters, the entire column is wrapped in double quotes.
/// </summary>
protected char[] SpecialChars = new char[] { ',', '"', '\r', '\n' }; // Indexes into SpecialChars for characters with specific meaning
private const int DelimiterIndex = ;
private const int QuoteIndex = ; /// <summary>
/// Gets/sets the character used for column delimiters.
/// </summary>
public char Delimiter
{
get { return SpecialChars[DelimiterIndex]; }
set { SpecialChars[DelimiterIndex] = value; }
} /// <summary>
/// Gets/sets the character used for column quotes.
/// </summary>
public char Quote
{
get { return SpecialChars[QuoteIndex]; }
set { SpecialChars[QuoteIndex] = value; }
}
} /// <summary>
/// Class for reading from comma-separated-value (CSV) files
/// </summary>
public class CsvFileReader : CsvFileCommon, IDisposable
{
// Private members
private StreamReader Reader;
private string CurrLine;
private int CurrPos;
private EmptyLineBehavior EmptyLineBehavior; /// <summary>
/// Initializes a new instance of the CsvFileReader class for the
/// specified stream.
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <param name="emptyLineBehavior">Determines how empty lines are handled</param>
public CsvFileReader(Stream stream,
EmptyLineBehavior emptyLineBehavior = EmptyLineBehavior.NoColumns)
{
Reader = new StreamReader(stream);
EmptyLineBehavior = emptyLineBehavior;
} /// <summary>
/// Initializes a new instance of the CsvFileReader class for the
/// specified file path.
/// </summary>
/// <param name="path">The name of the CSV file to read from</param>
/// <param name="emptyLineBehavior">Determines how empty lines are handled</param>
public CsvFileReader(string path,
EmptyLineBehavior emptyLineBehavior = EmptyLineBehavior.NoColumns)
{
Reader = new StreamReader(path);
EmptyLineBehavior = emptyLineBehavior;
} /// <summary>
/// Reads a row of columns from the current CSV file. Returns false if no
/// more data could be read because the end of the file was reached.
/// </summary>
/// <param name="columns">Collection to hold the columns read</param>
public bool ReadRow(List<string> columns)
{
// Verify required argument
if (columns == null)
throw new ArgumentNullException("columns"); ReadNextLine:
// Read next line from the file
CurrLine = Reader.ReadLine();
CurrPos = ;
// Test for end of file
if (CurrLine == null)
return false;
// Test for empty line
if (CurrLine.Length == )
{
switch (EmptyLineBehavior)
{
case EmptyLineBehavior.NoColumns:
columns.Clear();
return true;
case EmptyLineBehavior.Ignore:
goto ReadNextLine;
case EmptyLineBehavior.EndOfFile:
return false;
}
} // Parse line
string column;
int numColumns = ;
while (true)
{
// Read next column
if (CurrPos < CurrLine.Length && CurrLine[CurrPos] == Quote)
column = ReadQuotedColumn();
else
column = ReadUnquotedColumn();
// Add column to list
if (numColumns < columns.Count)
columns[numColumns] = column;
else
columns.Add(column);
numColumns++;
// Break if we reached the end of the line
if (CurrLine == null || CurrPos == CurrLine.Length)
break;
// Otherwise skip delimiter
Debug.Assert(CurrLine[CurrPos] == Delimiter);
CurrPos++;
}
// Remove any unused columns from collection
if (numColumns < columns.Count)
columns.RemoveRange(numColumns, columns.Count - numColumns);
// Indicate success
return true;
} /// <summary>
/// Reads a quoted column by reading from the current line until a
/// closing quote is found or the end of the file is reached. On return,
/// the current position points to the delimiter or the end of the last
/// line in the file. Note: CurrLine may be set to null on return.
/// </summary>
private string ReadQuotedColumn()
{
// Skip opening quote character
Debug.Assert(CurrPos < CurrLine.Length && CurrLine[CurrPos] == Quote);
CurrPos++; // Parse column
StringBuilder builder = new StringBuilder();
while (true)
{
while (CurrPos == CurrLine.Length)
{
// End of line so attempt to read the next line
CurrLine = Reader.ReadLine();
CurrPos = ;
// Done if we reached the end of the file
if (CurrLine == null)
return builder.ToString();
// Otherwise, treat as a multi-line field
builder.Append(Environment.NewLine);
} // Test for quote character
if (CurrLine[CurrPos] == Quote)
{
// If two quotes, skip first and treat second as literal
int nextPos = (CurrPos + );
if (nextPos < CurrLine.Length && CurrLine[nextPos] == Quote)
CurrPos++;
else
break; // Single quote ends quoted sequence
}
// Add current character to the column
builder.Append(CurrLine[CurrPos++]);
} if (CurrPos < CurrLine.Length)
{
// Consume closing quote
Debug.Assert(CurrLine[CurrPos] == Quote);
CurrPos++;
// Append any additional characters appearing before next delimiter
builder.Append(ReadUnquotedColumn());
}
// Return column value
return builder.ToString();
} /// <summary>
/// Reads an unquoted column by reading from the current line until a
/// delimiter is found or the end of the line is reached. On return, the
/// current position points to the delimiter or the end of the current
/// line.
/// </summary>
private string ReadUnquotedColumn()
{
int startPos = CurrPos;
CurrPos = CurrLine.IndexOf(Delimiter, CurrPos);
if (CurrPos == -)
CurrPos = CurrLine.Length;
if (CurrPos > startPos)
return CurrLine.Substring(startPos, CurrPos - startPos);
return String.Empty;
} // Propagate Dispose to StreamReader
public void Dispose()
{
Reader.Dispose();
}
} /// <summary>
/// Class for writing to comma-separated-value (CSV) files.
/// </summary>
public class CsvFileWriter : CsvFileCommon, IDisposable
{
// Private members
private StreamWriter Writer;
private string OneQuote = null;
private string TwoQuotes = null;
private string QuotedFormat = null; /// <summary>
/// Initializes a new instance of the CsvFileWriter class for the
/// specified stream.
/// </summary>
/// <param name="stream">The stream to write to</param>
public CsvFileWriter(Stream stream)
{
Writer = new StreamWriter(stream);
} /// <summary>
/// Initializes a new instance of the CsvFileWriter class for the
/// specified file path.
/// </summary>
/// <param name="path">The name of the CSV file to write to</param>
public CsvFileWriter(string path)
{
Writer = new StreamWriter(path);
} /// <summary>
/// Writes a row of columns to the current CSV file.
/// </summary>
/// <param name="columns">The list of columns to write</param>
public void WriteRow(List<string> columns)
{
// Verify required argument
if (columns == null)
throw new ArgumentNullException("columns"); // Ensure we're using current quote character
if (OneQuote == null || OneQuote[] != Quote)
{
OneQuote = String.Format("{0}", Quote);
TwoQuotes = String.Format("{0}{0}", Quote);
QuotedFormat = String.Format("{0}{{0}}{0}", Quote);
} // Write each column
for (int i = ; i < columns.Count; i++)
{
// Add delimiter if this isn't the first column
if (i > )
Writer.Write(Delimiter);
// Write this column
if (columns[i].IndexOfAny(SpecialChars) == -)
Writer.Write(columns[i]);
else
Writer.Write(QuotedFormat, columns[i].Replace(OneQuote, TwoQuotes));
}
Writer.WriteLine();
} // Propagate Dispose to StreamWriter
public void Dispose()
{
Writer.Dispose();
}
}
}
C# - CSV(Comma-Separated Values)文件读取.的更多相关文章
- python开发_csv(Comma Separated Values)_逗号分隔值_常用导入导出格式_完整版_博主推荐
## 最近出了一趟差,是从20号去的,今天回来...# 就把最近学习的python内容给大家分享一下...#''' 在python中,CSV(Comma Separated Values),从字面上面 ...
- Python文件处理(txt、csv文件读取)
打开文件 使用Python内置的方法 open()可以打开文件 file object = open(file_name [, access_mode][, buffering]) file_name ...
- CSV文件读取类
最近项目中,经常需要读取Csv文件.基本步骤是: (1)按行读取 (2)然后将一行数据按逗号,分割为字符串数组 (3)将各列字符串转换成相应类型的数据 ,如int double类型 写了一个简单的Cs ...
- 本地文件读取(csv,txt)时字符编码问题解决
今天进行csv文件读取时,老是入库为空,因为其中有中文字符,我要通过中文字符映射成相应的编号(上升:1011,下降:1012),于是怎么也取不到编号.刚开始以为程序映射出了问题,最后日志打出来后,发现 ...
- csv、json 文件读取
1.CSV 文件存储 1.1 写入 简单示例 import csv with open('data.csv', 'a') as csvfile: writer = csv.writer(csvfile ...
- cocos2d-x CSV文件读取 (Excel生成csv文件)
实现类 CCSVParse.h #ifndef __C_CSV_PARSE__ #define __C_CSV_PARSE__ #include "cocos2d.h" #incl ...
- 计算机程序的思维逻辑 (64) - 常见文件类型处理: 属性文件/CSV/EXCEL/HTML/压缩文件
对于处理文件,我们介绍了流的方式,57节介绍了字节流,58节介绍了字符流,同时,也介绍了比较底层的操作文件的方式,60节介绍了随机读写文件,61节介绍了内存映射文件,我们也介绍了对象的序列化/反序列化 ...
- Java编程的逻辑 (64) - 常见文件类型处理: 属性文件/CSV/EXCEL/HTML/压缩文件
本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...
- Python编码/文件读取/多线程
Python编码/文件读取/多线程 个人笔记~~记录才有成长 编码/文件读取/多线程 编码 常用的一般是gbk.utf-8,而在python中字符串一般是用Unicode来操作,这样才能按照单个字 ...
随机推荐
- startActivityForResult
Activity提供了startActivityForResult(Intent intent, int requestCode)方法打开新的Activity,新的Activity关闭后会向前面的Ac ...
- 在Activity之间如何传递数据,请尽可能说出你所知道的传递数据的方法,并详细描述其实现过程。
在Activity之间如何传递数据,请尽可能说出你所知道的传递数据的方法,并详细描述其实现过程. 答案:可以通过Intent对象.静态变量.剪切板和全局对象进行数据传递,具体的数据传递方法如下. 1. ...
- Mysql 5.6 Cmake 编译安装
MySQL编译安装 环境: OS: CentOS 6.6x64 mini mysql: mysql-5.6.251. mysql 下载: http://dev.mysql.com/downloads/ ...
- Sql Server索引(转载)
官方说法: 聚集索引 一种索引,该索引中键值的逻辑顺序决定了表中相应行的物理顺序. 聚集索引确定表中数据的物理顺序.聚集索引类似于电话簿,后者按姓氏排列数据.由于聚集索引规定数据在表中的物理存储顺序, ...
- centos 下使用sublime
CentOS 之 Sublime text3 安装及配置(不支持中文输入) sublime text 的界面友好,自动补全功能也不错. (本来用vim+php_function.txt的形式进行补全的 ...
- CSS强制图片大小
相信大家做网页时经常会碰到大分辨率的图片会把表格涨破以致漂亮的网页面目全非,但只要使用以下的CSS语句即可解决. 该CSS的功能是:大于600的图片自动调整为600显示. <style type ...
- day03
1.set集合--无序的,不重复的序列,类似dict,但是只有key,没有value 创建一个集合: s1 = {11,22,33} s2 = set((22,33,44))必须传入一个可迭代对象(t ...
- logisticregression
from numpy import * import random import time st = time.time() def loaddata(filename): fr = open(''. ...
- C++虚函数表解析(转)
C++中的虚函数的作用主要是实现了多态的机制.关于多态,简而言之就是用父类型别的指针指向其子类的实例,然后通过父类的指针调用实际子类的成员函数.这种技术可以让父类的指针有“多种形态”,这是一种泛型技术 ...
- Local System/Network Service/Local Service
// The name of the account under which the service should run// 1 NT AUTHORITY\\SYSTEM 2 NT AUTHORIT ...