参考链接:

https://www.cnblogs.com/lulianqi/p/6385503.html

http://blog.csdn.net/paul342/article/details/22800137

说明:

1.写入一个单元格时,如果含有逗号,则需要将整个字段用双引号括起来;如果里面还有双引号就替换成两个双引号。

2.写入一行时,末尾要加上\r\n作为行分隔符。

3.读取时,也要根据上面的写入规则进行解析。

代码如下:

 using System;
using System.Collections.Generic;
using System.IO;
using System.Text; public class CSVTool { private static char _csvSeparator = ',';
private static bool _trimColumns = false; //获取一个单元格的写入格式
public static string GetCSVFormat(string str)
{
string tempStr = str;
if (str.Contains(","))
{
if (str.Contains("\""))
{
tempStr = str.Replace("\"", "\"\"");
}
tempStr = "\"" + tempStr + "\"";
}
return tempStr;
} //获取一行的写入格式
public static string GetCSVFormatLine(List<string> strList)
{
string tempStr = "";
for (int i = ; i < strList.Count - ; i++)
{
string str = strList[i];
tempStr = tempStr + GetCSVFormat(str) + ",";
}
tempStr = tempStr + GetCSVFormat(strList[strList.Count - ]) + "\r\n";
return tempStr;
} //解析一行
public static List<string> ParseLine(string line)
{
StringBuilder _columnBuilder = new StringBuilder();
List<string> Fields = new List<string>();
bool inColumn = false; //是否是在一个列元素里
bool inQuotes = false; //是否需要转义
bool isNotEnd = false; //读取完毕未结束转义
_columnBuilder.Remove(, _columnBuilder.Length); //空行也是一个空元素,一个逗号是2个空元素
if (line == "")
{
Fields.Add("");
} // Iterate through every character in the line
for (int i = ; i < line.Length; i++)
{
char character = line[i]; // If we are not currently inside a column
if (!inColumn)
{
// If the current character is a double quote then the column value is contained within
// double quotes, otherwise append the next character
inColumn = true;
if (character == '"')
{
inQuotes = true;
continue;
} } // If we are in between double quotes
if (inQuotes)
{
if ((i + ) == line.Length)//这个字符已经结束了整行
{
if (character == '"') //正常转义结束,且该行已经结束
{
inQuotes = false;
continue; //当前字符不用添加,跳出后直结束后会添加该元素
}
else //异常结束,转义未收尾
{
isNotEnd = true;
}
}
else if (character == '"' && line[i + ] == _csvSeparator) //结束转义,且后面有可能还有数据
{
inQuotes = false;
inColumn = false;
i++; //跳过下一个字符
}
else if (character == '"' && line[i + ] == '"') //双引号转义
{
i++; //跳过下一个字符
}
else if (character == '"') //双引号单独出现(这种情况实际上已经是格式错误,为了兼容可暂时不处理)
{
throw new Exception("格式错误,错误的双引号转义");
}
//其他情况直接跳出,后面正常添加 }
else if (character == _csvSeparator)
inColumn = false; // If we are no longer in the column clear the builder and add the columns to the list
if (!inColumn) //结束该元素时inColumn置为false,并且不处理当前字符,直接进行Add
{
Fields.Add(_trimColumns ? _columnBuilder.ToString().Trim() : _columnBuilder.ToString());
_columnBuilder.Remove(, _columnBuilder.Length); }
else // append the current column
_columnBuilder.Append(character);
} // If we are still inside a column add a new one (标准格式一行结尾不需要逗号结尾,而上面for是遇到逗号才添加的,为了兼容最后还要添加一次)
if (inColumn)
{
if (isNotEnd)
{
_columnBuilder.Append("\r\n");
}
Fields.Add(_trimColumns ? _columnBuilder.ToString().Trim() : _columnBuilder.ToString());
}
else //如果inColumn为false,说明已经添加,因为最后一个字符为分隔符,所以后面要加上一个空元素
{
Fields.Add("");
} return Fields;
} //读取文件
public static List<List<string>> Read(string filePath, Encoding encoding)
{
List<List<string>> result = new List<List<string>>();
string content = File.ReadAllText(filePath, encoding);
string[] lines = content.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = ; i < lines.Length; i++)
{
List<string> line = ParseLine(lines[i]);
result.Add(line);
}
return result;
} //写入文件
public static void Write(string filePath, Encoding encoding, List<List<string>> result)
{
StringBuilder builder = new StringBuilder();
for (int i = ; i < result.Count; i++)
{
List<string> line = result[i];
builder.Append(GetCSVFormatLine(line));
}
File.WriteAllText(filePath, builder.ToString(), encoding);
} //打印
public static void Debug(List<List<string>> result)
{
for (int i = ; i < result.Count; i++)
{
List<string> line = result[i];
for (int j = ; j < line.Count; j++)
{
UnityEngine.Debug.LogWarning(line[j]);
}
}
}
}

测试:

[Unity工具]CSV工具类的更多相关文章

  1. CSV工具类

    分享自己昨天写的CSV工具类, 主要实现解析CSV格式, 直接上代码 #region private /// <summary> /// 从sr当前位置解析一个栏位 /// </su ...

  2. Unity自动打包工具

    转载 https://blog.csdn.net/ynnmnm/article/details/36774715 最开始有写打包工具的想法,是因为看到<啪啪三国>王伟峰分享的一张图,他们有 ...

  3. 多测师讲解常用的测试工具分为10类_高级讲师肖sir

    我们将常用的测试工具分为10类. 1. 测试管理工具 2. 接口测试工具 3. 性能测试工具 4. C/S自动化工具 5.白盒测试工具 6.代码扫描工具 7.持续集成工具 8.网络测试工具 9.app ...

  4. 使用工厂方法模式设计能够实现包含加法(+)、减法(-)、乘法(*)、除法(/)四种运算的计算机程序,要求输入两个数和运算符,得到运算结果。要求使用相关的工具绘制UML类图并严格按照类图的设计编写程序实

    2.使用工厂方法模式设计能够实现包含加法(+).减法(-).乘法(*).除法(/)四种运算的计算机程序,要求输入两个数和运算符,得到运算结果.要求使用相关的工具绘制UML类图并严格按照类图的设计编写程 ...

  5. 1、使用简单工厂模式设计能够实现包含加法(+)、减法(-)、乘法(*)、除法(/)四种运算的计算机程序,要求输入两个数和运算符,得到运算结果。要求使用相关的工具绘制UML类图并严格按照类图的设计编写程

    1.使用简单工厂模式设计能够实现包含加法(+).减法(-).乘法(*).除法(/)四种运算的计算机程序,要求输入两个数和运算符,得到运算结果.要求使用相关的工具绘制UML类图并严格按照类图的设计编写程 ...

  6. Atitit s2018.5 s5 doc list on com pc.docx  Acc 112237553.docx Acc baidu netdisk.docx Acc csdn 18821766710 attilax main num.docx Atiitt put post 工具 开发工具dev tool test.docx Atiitt 腾讯图像分类相册管家.docx

    Atitit s2018.5 s5  doc list on com pc.docx  Acc  112237553.docx Acc baidu netdisk.docx Acc csdn 1882 ...

  7. 在ArcEngine中使用Geoprocessing工具-执行工具

    转自原文在ArcEngine中使用Geoprocessing工具-执行工具 来解析一下Geoprocessor类的Execute方法,他有两种重载,Execute(IGPProcess, ITrack ...

  8. Unity C# CSV文件解析与加载(已更新移动端处理方式)

    在游戏开发过程中,经常要用到Excel编辑各类数据,如果可以直接用Excel支持的文件格式来读取数据,修改将非常便捷. Excel支持导出CSV类型的文件,这类文件不仅可以用Excel直接打开修改,即 ...

  9. C#操作CSV存取类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

随机推荐

  1. 语义分析之ansj_seg+word2vec的使用

    语义分析,我是一个初学者,有很多东西,需要理论和实践结合后,才能理解的相对清楚. 今天,我就在语义理解中基于背景语料的情况,实现语义上下文的预测,比如,我说“王宝强”,你会想到什么?别告诉没有“马蓉” ...

  2. 开源截图工具cutycapt的安装及使用

    之前在安装过程中碰到很多问题,也找了不少资料.现总结了下,给有需要的朋友.centos下安装cutycapt比较麻烦,需要先安装qt47,再下载cutycapt源码编译;而在ubuntu下安装cuty ...

  3. DelphiXE5如何获取Android手机SIM卡串号[转]

    手机号不是存在SIM卡上的,SIM卡只有一个串号.在运营商的服务器上有手机号和序号对应的一张表.所以你SIM卡办理遗失,运营商只要把新SIM卡的串号和你原来的手机号绑定即可. 获取手机号的唯一办法是收 ...

  4. django 数据模型中 null=True 和 blank=True 有什么区别

    null: If True, Django will store empty values as NULL in the database. Default is False. 如果为True,空值将 ...

  5. 车载文档记录(ROM)

    一,缩写词定义 1,ECU和ECM ECU: Engine Control Unit 发动机控制单元:从用途上讲则是汽车专用微机控制器.ECM: Engine Control Module 发动机控制 ...

  6. Windows Azure Virtual Network (12) 虚拟网络之间点对点连接VNet Peering

    <Windows Azure Platform 系列文章目录> 在有些时候,我们需要通过VNet Peering,把两个虚拟网络通过内网互通互联.比如: 1.在订阅A里的Virtual N ...

  7. [原抄] Potplayer 1.7.2710 快捷键

    对着软件一个一个抄下来的. 打开文件:Ctrl+O[F3] / 简索文件:F12 / 最后文件 Ctrl+Y / 关闭:F4 打开摄像头:Ctrl+J / 打开DVD设备 Ctrl+D 播放.暂停:空 ...

  8. vlan交换机的端口模式有哪几种

    一 端口类型1 ,Access用户模式2 ,Trunk链路模式3 ,Hybrid模式(跟Trunk很类似但比trunk高级)二 端口介绍2.1 ,Access类型端口:只允许默认vlan的以太网帧,也 ...

  9. linux 系统下有sda和hda的硬件设备分别代表什么意思

    linux 系统下有sda和hda的硬件设备分别代表什么意思/dev/sda1 # SCSI设备,sda,sdb,sdc,三块盘,1,2,3代表分区(PV)/dev/sda2/dev/sdb1/dev ...

  10. Ubuntu 14.10 下编译Hadoop2.4.0

    在http://www.aboutyun.com/thread-8130-1-1.html 这里看到到,安装过程遇到了上面说的问题,所以将此文转载过来,以备不时之需,感谢此作者. 问题导读: 1.如果 ...