unity3d:csv读取数据,兼容单元格中包含逗号

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

四夕立羽

你的鼓励将是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值