Unity 读取Excel

时间:2023-01-08 05:54:28

游戏有大多数配置文件,比如玩家等级,游戏商店信息等等.通常情况下把这些放入excel中来读取

第一种解决方案:

xlsx –> csv –> 改变成UTF-8 或者Unicode编码 –> 修改后缀名成.txt  -> 通过Resources.Load读取转换成TextAsset –> 通过,方式开区分开来

Unity 读取Excel

转换成csv(软件采用notepad++)

Unity 读取Excel

项目图:

Unity 读取Excel

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Text; public class Test : MonoBehaviour { private string[] lineArray;
private CSVTable table; public void OnGUI()
{
if (GUI.Button(new Rect(, , , ), "读取Excel"))
{
TextAsset text = (TextAsset)Resources.Load("data", typeof(TextAsset));
lineArray = text.text.Split("\r"[]); table = new CSVTable();
for (int i = ; i < lineArray.Length; i++)
{
table.AddRow(lineArray[i]);
} //输出每行的信息
for (int i = ; i < table.rows.Count; i++)
{
Debug.Log(table.rows[i].ToString());
} Debug.Log("=========================="); //还是输出每行的信息
for (int i = ; i < table.rows.Count; i++)
{
Debug.Log(table.rows[i][] + "-" + table.rows[i][]); } #region 信息输出
/*
string[] row;
string info = string.Empty;
for (int j = 0; j < lineArray.Length; j++)
{
row = lineArray[j].Split(',');
for (int i = 0; i < row.Length; i++)
{
info += "-" + row[i];
} info = info.TrimStart('-');
Debug.Log(info);
info = string.Empty;
}*/
#endregion }
} } /// <summary>
/// 表示一行
/// </summary>
public struct Row
{
public string rowText;
public List<Coll> colls; public Row(string line)
{
rowText = line;
string [] tempColls = line.Split(','); colls = new List<Coll>();
for (int i = ; i < tempColls.Length; i++)
{
colls.Add(new Coll(tempColls[i]));
}
} public string GetCell(int index)
{
return colls[index].ToString();
} public string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < colls.Count; i++)
{
sb.Append("-" + colls[i].ToString()); }
//去掉最后的"-"
return sb.ToString().TrimStart('-');
} /// <summary>
/// 让结构可以直接[下标值] 来获取或设置 单元格的字符串
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public string this[int index]
{
get
{
return colls[index].ToString();
}
set
{
this.colls[index].SetText(value);
}
} } /// <summary>
/// 每一个单元格
/// </summary>
public struct Coll
{
public string cellText; public Coll(string cell)
{
cellText = cell;
} /// <summary>
/// 写一个ToString()方便获取字符串
/// </summary>
/// <returns></returns>
public string ToString()
{
return cellText;
} /// <summary>
/// 设置单元格的字符串
/// </summary>
/// <param name="text"></param>
public void SetText(string text)
{
cellText = text;
} } /// <summary>
/// 一张表
/// </summary>
public struct CSVTable
{
/// <summary>
/// 行集合
/// </summary>
public List<Row> rows; /// <summary>
/// 增加一行数据
/// </summary>
/// <param name="line">以","分割的一行文本</param>
public void AddRow(string line)
{
if (rows == null)
{
rows = new List<Row>();
}
rows.Add(new Row(line));
} }