首先导入Excel.dll,ICSharpCode.SharpZipLib.dll,System.Data.dll这些库,下载地址如下:
链接:https://pan.baidu.com/s/1oSaR1jYmSIHC8pRqDJFsUQ
提取码:4gmc
创建Excel表格数据
这里创建一个Test.xlsx:
这里的数据读取之后,序列化保存到本地。
序列化的保存:
1.创建数据类Goods(这里需要加上可序列化标签Serializable,这样到时后也可方便我们查看)
[System.Serializable]
public class Goods
{
public uint id; //物品id
public string name; //物品名字
public uint price; //物品价格
public string describe; //物品描述
}
2.创建这个保存所有数据的类Data
继承ScriptableObject实例生成一个UnityEngine.Object文件
using UnityEngine;
public class Data : ScriptableObject
{
public Goods[] goods;
}
3.读取excel内容ExcelRead
导入命名空间:
using Excel;
using System.Data;
using System.IO;
public static class ExcelRead
{
/// 获取excel表格里面的数据
public static Goods[] ReadGoodsExcel(string filePath)
{
//这里的用List存储 可避免一些空行的保存
List<Goods> list = new List<Goods>();
int columnNum = 0, rowNum = 0;//excel 行数 列数
DataRowCollection collect = ReadExcel(filePath, ref columnNum, ref rowNum);
//这里i从1开始遍历, 因为第一行是标签名
for (int i = 1; i < rowNum; i++)
{
//如果改行是空行 不保存
if (IsEmptyRow(collect[i], columnNum)) continue;
Goods goods = new Goods();
uint.TryParse(collect[i][0].ToString(), out goods.id);
goods.name = collect[i][1].ToString();
uint.TryParse(collect[i][2].ToString(), out goods.price);
goods.describe = collect[i][3].ToString();
list.Add(goods);
}
return list.ToArray();
}
//判断是否是空行
static bool IsEmptyRow(DataRow collect, int columnNum)
{
for (int i = 0; i < columnNum; i++)
{
if (!collect.IsNull(i)) return false;
}
return true;
}
/// <summary>
/// 读取excel文件内容获取行数 列数 方便保存
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="columnNum">行数</param>
/// <param name="rowNum">列数</param>
/// <returns></returns>
static DataRowCollection ReadExcel(string filePath, ref int columnNum, ref int rowNum)
{
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
//Tables[0] 下标0表示excel文件中第一张表的数据
columnNum = result.Tables[0].Columns.Count;
rowNum = result.Tables[0].Rows.Count;
return result.Tables[0].Rows;
}
}
4.一键保存数据到Resources文件夹下
创建ExcelReadEditor类,工具类需要保存到Editor文件夹下,这个文件打包的时候不会被打进去,同时需要继承Unity的Editor类
public class ExcelReadEditor : Editor
{
//读取的excel文件路径
public static readonly string filePath = Application.dataPath + "/Excel/" + "Test.xlsx";
[MenuItem("Excel/读取测试数据")]
public static void CreateSignInData()
{
Data manager = CreateInstance<Data>(); //数据载体
manager.goods = ExcelRead.ReadGoodsExcel(filePath);
string path = "Assets/Resources/" + "Test.asset"; //保存到Resources文件下
AssetDatabase.CreateAsset(manager, path);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("读取数据成功");
}
}
终于一切准备就绪,最后在Unity菜单项,Excel->读取测试数据。就可以生成我们需要的Asset文件了!
点击生成Test文,件在Inspector窗口查看:
再加上一个Debug测试,大功告成啦