Excel的第三方库https://github.com/ExcelDataReader/ExcelDataReader
打开上面的Github地址。克隆库到本地,然后解压Zip后打开文件夹。
用VS打开Vs解决方案.sln,生成解决方案。
之后在工程目录下找到下面的这个文件夹中选中的三个文件,拖入Assets/Plugins/下。
还有这个,Unity安装目录的System.Data.dll 放入工程里。
如图
using System.Data;
using System.IO;
using ExcelDataReader;
using UnityEngine;
public class ReadExcelMyTools : MonoBehaviour
{
private string FilePath;
private void Start()
{
FilePath = Application.dataPath + "/../Excels/LevelInfo.xlsx";
//Debug.Log(FilePath);
ReadExcelStream();
}
private void ReadExcelStream()
{
FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelDataReader.AsDataSet();
int columns = result.Tables[0].Columns.Count;
int rows = result.Tables[0].Rows.Count;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
string nvalue = result.Tables[0].Rows[i][j].ToString();
Debug.Log("row :" + i.ToString() + " column :" + j.ToString() + "+++++" + nvalue);
}
}
excelDataReader.Close();
}
}
excel表放在Assets同级目录,当然也可以放在别处。
有人说报错,把安装目录下面的 I18N 开头的也导入工程。
编辑器模式
using System.Data;
using System.IO;
using ExcelDataReader;
using UnityEditor;
using UnityEngine;
public class ReadExcelEditorMyTools
{
[MenuItem("MyExcel/ReadExcel", false, 0)]
static void ReadExcel()
{
string FilePath = Application.dataPath + "/../Excels/LevelInfo.xlsx";
FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelDataReader.AsDataSet();
int columns = result.Tables[0].Columns.Count;
int rows = result.Tables[0].Rows.Count;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
string nvalue = result.Tables[0].Rows[i][j].ToString();
Debug.Log("row :" + i.ToString() + " column :" + j.ToString() + "+++++" + nvalue);
}
}
excelDataReader.Close();
}
}