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来操作,这样才能按照单个字 ...
随机推荐
- QT学习:入门篇(三)
头文件: #ifndef CChatDisplaySet_h #define CChatDisplaySet_h #include "QtGui/QDialog" #include ...
- 热门usb无线网卡
拓实 N910 N95 N82 N81 N89 都是3070的 拓实 N87 G618 是8187的硬功夫 216 310 217 218 300 315 335 350 370 380 510 53 ...
- 用存储过程生成订单号ID
DECLARE @sonumber BIGINTSELECT @sonumber=CONVERT(BIGINT, @serverId + Substring(CONVERT(VARCHAR(4), D ...
- 使用SQLiteDatabase进行数据库操作的步骤
1.获取SQLiteDatabase对象,它代表了与数据库的连接.2.调用SQLiteDatabase的方法来执行SQL语句.3.操作SQL语句的执行结果,比如用SimpleCursorAdapter ...
- Altium Designer如何批量修改名称,数值,封装
方法一: altium里的封装管理库 1,Tools -> Footprint Manager -> ...2,在Component List里选择要改的器件3,在View and Edi ...
- 如何把SKYPE的发送消息由enter改为ctrl+enter?
如果您的skype是tom-skype3.8正式版.您可以在skype面板中,选择"工具"-"选项"-"会话"-"会话设置&quo ...
- delphi7调用webservice Java 传入参数为空
在delphi7中,new-webservices-wsdl importer中输入wsdl地址,会自动生成wsdl单元代码.在调用时,传入参数到服务器端时为空了. 网上说缺少 InvRegistry ...
- 14条Yahoo(雅虎)十四条优化原则【转】
请大家都能好好学习,不要像我一样一扫而过,好好的记下来!不仅仅是晓得一些CSS xhtml就好了,深刻认识到很多的东西需要学习的.很早就用Firebug,但是却没听说过Yslow,这叫不喜欢追求.希望 ...
- 百度全站变https
今天打开百度首页,突然发现,百度的网址变为 https://www.baidu.com/,如下图: 好嘛,以后再也不怕别人使用抓包工具查看我在百度的搜索数据了.当年的Duck Duck Go就是因为是 ...
- SQL 查询某字段id为空(不为空)
1 sql 查询某字段id为空 select * from 表名 where id is null ; 2 sql 查询某字段id不为空 select * from 表名 wher ...