参考链接:

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. 基于nginx + lua实现的反向代理动态更新

    大家都知道,nginx是当前应用非常广泛的web服务器,热度因为他的高并发高性能高可靠性,且轻量级!牛逼的不行,不多说这些. 今天要介绍的是,如何基于nginx和lua脚本,也就是在openresty ...

  2. JavaScript跟踪-Piwik

    1.先决条件:使用新版本的JavaScript跟踪代码 2.JavaScript跟踪代码的功能 (1)自定义在Piwik中显示的页面名称 (2)手动触发目标转化 (3)考虑一个主机的“别名”,不将这个 ...

  3. 阅读 ‘External Memory PHY Interface (ALTMEMPHY)’笔记

    阅读 ‘External Memory PHY Interface (ALTMEMPHY)’笔记 1.PLL reference clock frequency 此处控制器输入时钟设置为100MHz, ...

  4. JAVA常量与变量

    顺着箭头的转换为自动转换逆这箭头的转换为强制转换. 常量 关键字FINAL 命名为大写 标识符 1要以字母数字下划线和¥组成 2首字母不能为数字 3不能是JAVA的关键字和 保留字 4数据类型分为基本 ...

  5. Maven 之多模块构建

    项目的打包类型:pom.jar.war 项目中一般使用maven进行模块管理,每个模块下对应都有一个pom文件,pom文件中维护了各模块之间的依赖和继承关系.项目模块化可以将通用的部分抽离出来,方便重 ...

  6. WPF DataGrid 导出Excel

    #region Excel导出 private void btnExportExcel_Click(object sender, RoutedEventArgs e) { Export(this.dg ...

  7. vue element-ui 用checkebox 来模拟选值 1/0

    https://jsfiddle.net/57dz2m3s/12/ 复制 粘贴 打开url就可以看到效果

  8. Centos7 安装sz,rz命令

    yum install lrzsz 我记得以前某个我敬佩的人说过压缩分很多种,有空,补充这篇笔记.加油~

  9. C++进阶--类的继承

    //############################################################################ /* * 公有,保护,私有继承 */ cl ...

  10. 1125 Chain the Ropes (25 分)

    1125 Chain the Ropes (25 分) Given some segments of rope, you are supposed to chain them into one rop ...