乐于分享
好东西不私藏

Unity开发安卓端应用如何加载表格数据

Unity开发安卓端应用如何加载表格数据

Unity加载表格一般用EPPlus,但是Android环境不支持 System.Configuration.ConfigurationManager,而 EPPlus 在初始化时默认会去读取 AppSettings 来确定 LicenseContext,必须手动设置 LicenseContext 才能避免读取 AppSettings。

因此在Android上直接用EPPlus会出现以下报错:System.Configuration.ConfigurationManager::get_AppSettings。

如果一定要用EPPlus的话,在任何 EPPlus 操作前添加以下代码:

ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

必须保证 EPPlus 版本 ≥ 5。

我只有4.x版本的EPPlus,没有找到EPPlus 5以上的版本,github上的源码build一直报错,所以为了能在安卓端加载表格数据,我选择另一种方式:将表格存储为csv格式,把 CSV 从 StreamingAssets 复制到持久目录再读取。

安卓对 StreamingAssets 的 jar 路径比较敏感,最稳妥的方案是:

List rows = new List();IEnumerator LoadCSV(){    string src = Application.streamingAssetsPath + "/data.csv";    string dst = Path.Combine(Application.persistentDataPath, "data.csv");    // 读取 StreamingAssets    UnityWebRequest request = UnityWebRequest.Get(src);    yield return request.SendWebRequest();    if (request.result != UnityWebRequest.Result.Success)    {        Debug.LogError(request.error);        yield break;    }    // 保存到本地    File.WriteAllBytes(dst, request.downloadHandler.data);    // 从持久目录读取    string csv = File.ReadAllText(dst);    Debug.Log("CSV 内容:" + csv);    string[] lines = csv.Split('\n');    foreach (string line in lines)    {        if (string.IsNullOrWhiteSpace(line))            continue;        // 去掉结尾换行        string cleanLine = line.Trim();        // 以逗号分列(基础方法)        string[] cols = cleanLine.Split(',');        rows.Add(cols);    }}