Unity 读取Excel文件 踩坑记录

Unity 读取 Excel 文件  

Unity读取Excel文件须要引入 dll 连接库:     编辑器

  • Excel.dll  
  • ICSharpCode.SharpZipLib   

同时添加 Unity 安装目录下的如下 dll 库文件:   excel

  • System.Data    (D:\Unity2018.2.3\Install\Editor\Data\Mono\lib\mono\2.0)
  • I18N.CJK.dll  
  • I18N.dll
  • I18N.MidEast.dll  
  • I18N.Other.dll  
  • I18N.Rare.dll  
  • I18N.West.dll     (D:\Unity2018.2.3\Install\Editor\Data\Mono\lib\mono\unity)    

坑1:I18N系列的 dll 库文件的添加主要是解决 编辑器下能够读取,打包.exe程序后,没法读取的状况    code

读取示例:   ip

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using System.Data;

using System.IO;

using Excel;

public class DoExcel {

    public static DataSet ReadExcel(string path)

    {

        FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);

        // CreateOpenXmlReader用于读取Excel2007版本及以上的文件

        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

        DataSet result = excelReader.AsDataSet();

        excelReader.Close();

        return result;

    }

    public static List<DepenceTableData> Load(string path)

    {

        List<DepenceTableData> _data = new List<DepenceTableData>();

        DataSet resultds = ReadExcel(path);

        int column = resultds.Tables[0].Columns.Count;

        int row = resultds.Tables[0].Rows.Count;

        Debug.LogWarning(column + "  " + row);

        for(int i=1;i<row;i++)

        {

            DepenceTableData temp_data;

            temp_data.instruct = resultds.Tables[0].Rows[i][0].ToString();

            temp_data.word = resultds.Tables[0].Rows[i][1].ToString();

            Debug.Log(temp_data.instruct + "  " + temp_data.word);

            _data.Add(temp_data);

        }

        return _data;

    }

}

public struct DepenceTableData

{

    public string word;

    public string instruct;

}

坑2:这里还有一个小问题须要注意下,就是关于Excel文件,有的时候Excel文件内的数据有效行可能不多,好比不到10行,可是Excel文件中右侧导航条会很长,拉到底会有一个巨大的行数,这里建议是将无效行的清除掉,不然Unity在读取时,会将这些无效行所有读取进去,这样会形成程序直接卡死string