C#如何读取csv格式文件
C#如何读取csv格式文件一、CSV文件规则
//读CSV文件类,读取指定的CSV文件,可以导出DataTable
public class CsvStreamReader
{
private ArrayList rowAL; //行链表,CSV文件的每一行就是一个链
private string fileName; //文件名
private Encoding encoding; //编码
public CsvStreamReader()
{
this.rowAL = new ArrayList();
this.fileName = "";
this.encoding = Encoding.Default;
}
/// <summary>
///
/// </summary>
/// <param name="fileName">文件名,包括文件路径</param>
public CsvStreamReader(string fileName)
{
this.rowAL = new ArrayList();
this.fileName = fileName;
this.encoding = Encoding.Default;
LoadCsvFile();
}
/// <summary>
///
/// </summary>
/// <param name="fileName">文件名,包括文件路径</param>
/// <param name="encoding">文件编码</param>
public CsvStreamReader(string fileName, Encoding encoding)
{
this.rowAL = new ArrayList();
this.fileName = fileName;
this.encoding = encoding;
LoadCsvFile();
}
/// <summary>
/// 文件名,包括文件路径
/// </summary>
public string FileName
{
set
{
this.fileName = value;
LoadCsvFile();
}
}
/// <summary>
/// 文件编码
/// </summary>
public Encoding FileEncoding
{
set
{
this.encoding = value;
}
}
/// <summary>
/// 获取行数
/// </summary>
public int RowCount
{
get
{
return this.rowAL.Count;
}
}
/// <summary>
/// 获取列数
/// </summary>
public int ColCount
{
get
{
int maxCol;
maxCol = 0;
for (int i = 0; i < this.rowAL.Count; i++)
{
ArrayList colAL = (ArrayList)this.rowAL[i];
maxCol = (maxCol > colAL.Count) ? maxCol : colAL.Count;
}
return maxCol;
}
}
/// <summary>
/// 获取某行某列的数据
/// row:行,row = 1代表第一行
/// col:列,col = 1代表第一列
/// </summary>
public string this[int row, int col]
{
get
{
//数据有效性验证
CheckRowValid(row);
CheckColValid(col);
ArrayList colAL = (ArrayList)this.rowAL[row - 1];
//如果请求列数据大于当前行的列时,返回空值
if (colAL.Count < col)
{
return "";
}
return colAL[col - 1].ToString();
}
}
/// <summary>
/// 根据最小行,最大行,最小列,最大列,来生成一个DataTable类型的数据
/// 行等于1代表第一行
/// 列等于1代表第一列
/// maxrow: -1代表最大行
/// maxcol: -1代表最大列
/// </summary>
public DataTable this[int minRow, int maxRow, int minCol, int maxCol]
{
get
{
//数据有效性验证
CheckRowValid(minRow);
CheckMaxRowValid(maxRow);
CheckColValid(minCol);
CheckMaxColValid(maxCol);
if (maxRow == -1)
{
maxRow = RowCount;
}
if (maxCol == -1)
{
maxCol = ColCount;
}
if (maxRow < minRow)
{
throw new Exception("最大行数不能小于最小行数");
}
if (maxCol < minCol)
{
throw new Exception("最大列数不能小于最小列数");
}
DataTable csvDT = new DataTable();
标签: