You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Unity与Excel制作工作指引:Excel导入及UI预制体实例化技术咨询

Unity导入Excel并解析生成UI预制体实现方案

前置准备

  • 导入适配Unity的EPPlus 4.x版本dll,放到项目Plugins文件夹下(该版本为MIT协议可免费商用,5.x及以上版本商用需付费)
  • 打开Player Settings,将Api Compatibility Level设置为.NET Framework,避免dll兼容报错

核心Excel解析脚本

using OfficeOpenXml;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class ExcelReader : MonoBehaviour
{
    /// <summary>
    /// 读取Excel指定工作表数据
    /// </summary>
    /// <param name="filePath">Excel文件路径</param>
    /// <param name="sheetIndex">工作表序号,从1开始</param>
    /// <returns>解析后的数据列表</returns>
    public List<ExcelData> ReadExcel(string filePath, int sheetIndex = 1)
    {
        List<ExcelData> resultList = new List<ExcelData>();
        if (!File.Exists(filePath))
        {
            Debug.LogError("Excel文件不存在:" + filePath);
            return resultList;
        }

        FileInfo fileInfo = new FileInfo(filePath);
        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets[sheetIndex];
            int rowCount = worksheet.Dimension.Rows;
            // 循环从2开始是跳过表头行,无表头可改为从1开始
            for (int i = 2; i <= rowCount; i++)
            {
                ExcelData data = new ExcelData();
                // 列索引从1开始,可根据自身Excel列结构调整字段映射
                data.uiPrefabId = int.Parse(worksheet.Cells[i, 1].Value?.ToString() ?? "0");
                data.uiTitle = worksheet.Cells[i, 2].Value?.ToString() ?? string.Empty;
                data.posX = float.Parse(worksheet.Cells[i, 3].Value?.ToString() ?? "0");
                data.posY = float.Parse(worksheet.Cells[i, 4].Value?.ToString() ?? "0");
                resultList.Add(data);
            }
        }
        return resultList;
    }
}

/// <summary>
/// 自定义Excel数据结构,和Excel列一一对应
/// </summary>
public class ExcelData
{
    // UI预制体ID,对应预制体列表的索引
    public int uiPrefabId;
    // UI显示的标题文本
    public string uiTitle;
    // UI在父容器中的锚点X坐标
    public float posX;
    // UI在父容器中的锚点Y坐标
    public float posY;
}

实例化UI预制体逻辑

using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class UISpawner : MonoBehaviour
{
    // Inspector面板提前挂载所有用到的UI预制体,索引对应Excel里的uiPrefabId
    public List<GameObject> uiPrefabList;
    // 生成UI的父容器,一般为Canvas下的布局组件
    public Transform uiRoot;

    public void GenerateUIFromExcel()
    {
        // 示例读取StreamingAssets目录下的Excel文件,打包后该目录可正常读写
        string excelPath = Path.Combine(Application.streamingAssetsPath, "WorkGuideData.xlsx");
        List<ExcelData> excelDatas = GetComponent<ExcelReader>().ReadExcel(excelPath);

        foreach (var data in excelDatas)
        {
            if (data.uiPrefabId < 0 || data.uiPrefabId >= uiPrefabList.Count)
            {
                Debug.LogWarning($"预制体ID{data.uiPrefabId}不存在,跳过生成");
                continue;
            }
            // 实例化预制体
            GameObject uiItem = Instantiate(uiPrefabList[data.uiPrefabId], uiRoot);
            // 设置UI位置
            uiItem.GetComponent<RectTransform>().anchoredPosition = new Vector2(data.posX, data.posY);
            // 赋值UI文本,可根据自身需求扩展其他字段赋值逻辑
            uiItem.GetComponentInChildren<TMPro.TMP_Text>().text = data.uiTitle;
        }
    }
}

注意事项

  • 优先使用.xlsx格式的Excel文件,.xls格式需要额外适配NPOI库,兼容成本更高
  • 如果不需要运行时动态修改Excel,可在Editor模式下提前将Excel数据解析后存储为ScriptableObject,省去运行时解析的性能开销
  • 打包发布前需要把用到的Excel文件放到StreamingAssets文件夹下,否则运行时无法读取到文件

内容的提问来源于stack exchange,提问作者MechanicalEngineer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:06:04