using UnityEngine;
using System.Linq;
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
public class CSV
{
public string[] header;
public List<string> lines;
}
public static class CSVReader {
private static readonly string splitter = "[liyu]";
private static readonly string[] splitters = new string[]{splitter};
public static CSV Read(string text)
{
CSV csv = new CSV();
text = text.Trim().Replace("\r", "") + "\n";
// read cells
csv.lines = new List<string>();
bool startCell = false;
StringBuilder line = new StringBuilder();
for(int i=0; i<text.Length; ++i)
{
char c = text[i];
if(c == '"')
{
if(text[i+1] == '"') i++;
else
{
startCell = !startCell;
continue;
}
}
else if(!startCell && c == ',')
{
line.Append(splitter);
continue;
}
else if(!startCell && c == '\n')
{
csv.lines.Add(line.ToString());
line.Length = 0;
continue;
}
line.Append(c);
}
string lastLine = line.ToString().Trim();
if(!string.IsNullOrEmpty(lastLine)) csv.lines.Add(lastLine);
// add line number
//csv.lines = csv.lines.Select((t, index) => string.Format("{0}{2}{1}", (index > 0 ? (index+1).ToString() : "line"), t, splitter)).ToList();
// get header
csv.header = ParseLine(csv.lines[0]);
csv.lines.RemoveAt(0);
return csv;
}
public static string[] ParseLine(string line)
{
return line.Split(splitters, StringSplitOptions.None);
}
}
public class CSVMgr
{
public static List<string[]> GetData(string path)
{
string tipString = JsonMgr.GetJsonString(Application.streamingAssetsPath + "/" + path);
List<string[]> rows = new List<string[]>();
CSV csv = CSVReader.Read(tipString);
csv.lines.ForEach(line => rows.Add(CSVReader.ParseLine(line)));
return rows;
}
public static List<string[]> GetDataFromRes(string path)
{
TextAsset ta = Resources.Load<TextAsset>(path);
string tipString = ta.text;
List<string[]> rows = new List<string[]>();
CSV csv = CSVReader.Read(tipString);
csv.lines.ForEach(line => rows.Add(CSVReader.ParseLine(line)));
return rows;
}
}
读取时把csv文件转化为List<string[]>,再用for循环进行解析
List<string[]> rows = new List<string[]>();
rows = CSVMgr.GetDataOri("CsvTest.csv");
for (int i = 0; i < rows.Count; i++)
{
m_dic[rows[i][0].ToString()] = rows[i][1].ToString();
}
由于excel导出csv不好转utf8,并且不能打开时跑程序,所以推荐个编辑器Ron‘s Editor csv编辑器https://www.ronsplace.eu/Products/RonsEditor/Download
编辑器中
用txt打开
说明: 1.如果单元格中包换了英文逗号,txt中会自动加上""包住整个单元格 2.如果单元格中包含了英文双引号,txt中会自动再加上一层双引号
所以,在程序读取时 1.先重新组装每一行,碰到单个字符为",判断后一个有无引号,有即是单元格中包含字符",无即是单元格中包含字符,
for (int i = 0; i < text.Length; ++i)
{
char c = text[i];
if (c == '"')
{
if (text[i + 1] == '"') i++;
else
{
startCell = !startCell;
continue;
}
}
else if (!startCell && c == ',')
{
line.Append(splitter);
continue;
}
else if (!startCell && c == '\n')
{
csv.lines.Add(line.ToString());
line.Length = 0;
continue;
}
line.Append(c);
}
2.判断到字符,作用是分隔符,用个字符串替"[liyu]"换它,解析时用这个特定字符Split切割,这样兼容单元格中包含逗号
line.Split(splitters, StringSplitOptions.None);