一、CSV文件
逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号或制表符。通常,所有记录都有完全相同的字段序列。通常都是纯文本文件。建议使用WORDPAD或是记事本来开启,再则先另存新档后用EXCEL开启,也是方法之一。
CSV文件格式的通用标准并不存在,但是在RFC 4180中有基础性的描述。使用的字符编码同样没有被指定,但是bitASCII是最基本的通用编码。
参照:https://zhuanlan.zhihu.com/p/628909380
二、使用规则
1、开头是不留空,以行为单位。
2、可含或不含列名,含列名则居文件第一行。
3、一行数据不跨行,无空行。
4、以半角逗号(即,)作分隔符,列为空也要表达其存在。
5、列内容如存在半角引号(即"),替换成半角双引号(“”)转义,即用半角引号(即"")将该字段值包含起来。
6、文件读写时引号,逗号操作规则互逆。
7、内码格式不限,可为 ASCII、Unicode 或者其他。
8、不支持数字
9、不支持特殊字符
参照:https://zhuanlan.zhihu.com/p/628909380
三、CSV读取操作类函数
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FileOperationsDemo
{
public static class ReadWriteCSV
{
#region 读写CSV文件
/// <summary>
/// 读取CSV文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>数据列表</returns>
public static List<string[]> ReadCSV(string filePath)
{
List<string[]> dataList = new List<string[]>();
StreamReader reader;
try
{
using (reader = new StreamReader(filePath, System.Text.Encoding.GetEncoding("GB2312")))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] data = line.Split(',');
dataList.Add(data);
}
}
}
catch (Exception ex)
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.ToUpper().Equals("EXCEL"))
process.Kill();
}
GC.Collect();
Thread.Sleep(50);
Console.WriteLine(ex.StackTrace);
using (reader = new StreamReader(filePath, System.Text.Encoding.GetEncoding("GB2312")))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] data = line.Split(',');
dataList.Add(data);
}
}
}
reader.