Unity跨平台(安卓)使用C#读取Excel的遇到的坑

昨天把项目打包发布在安卓平台时,发现一个功能的效果出错了。排查以后,发现是使用以前用的C#读取Excel的工具类ExcelReader读出来的数据是空的。(https://blog.csdn.net/KeeeepGO/article/details/83186377)

原因是在安卓平台上不能直接使用

string filePath = Application.streamingAssetsPath + "/" + excel_name;
FileStream fs = File.Open(filePath + excel_name, FileMode.Open, FileAccess.Read);

来读取Application.streamingAssetsPath的文件。

根据stackoverflow的说法,在安卓平台,必须通过WWW来读取Application.streamingAssetsPath的文件。(https://answers.unity.com/questions/1225077/using-streamingassets-in-android.html)

然而,WWW是个异步的,而我的工具类静态的,一运行就崩溃。

filePath = Application.streamingAssetsPath + "/" + excel_name;
WWW reader = new WWW(filePath);
while (!reader.isDone) { }
filePath = Application.streamingAssetsPath + "/";

于是,我掏出了另一个工具类TaskeManager(就是创建一个GameObject,通过它来使用协程)。

然而,WWW读出来的是text或者bytes怎么办嘞,我这依赖的Excel库的ExcelReaderFactory.CreateOpenXmlReader只能用Stream类型作为参数呀。

于是,我把读出来的bytes写进Application.persistentDataPath。这个路径的文件是不用www,可直接读写的。

    static IEnumerator copyFileToPersistent(string filePath,string excel_name)
    {
        string path = Application.persistentDataPath + "/" + excel_name;
        WWW www = new WWW(filePath);
        if (!File.Exists(path))
        { 
            yield return www;
            if (www.error == null)
            {
                File.WriteAllBytes(path, www.bytes);
            }
        } 
    }
    public static List<T> ReadFromExcel<T>(this List<T> current, string excel_name = "", string sheet_name = "") where T : ExcelData, new()
    { 
        string filePath = 
        Application.streamingAssetsPath + "/" + excel_name;

        Task task = new Task(copyFileToPersistent(filePath, excel_name));
        task.Start();
        while (!File.Exists(Application.persistentDataPath + "/" + excel_name))
        { }

        filePath = Application.persistentDataPath + "/";

然而,还是不行。

可能是因为这个Excel库不能在安卓平台使用?(https://blog.csdn.net/yupu56/article/details/50580277)

尝试在安卓系统运行环境打断点调试看看,然而可能机子不行,unity无限卡build。

暂时先用着上面那篇博客说的方法吧。

关于Unity的文件路径问题,可参考:

https://blog.csdn.net/u014147126/article/details/81276707

https://blog.csdn.net/ynnmnm/article/details/52253674

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值