Unity讀取Excel表格


一、將讀取Excel文件放到Plugins文件下,並添加組件

二、相關代碼

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data;
using System.IO;
using Excel;
using UnityEngine.UI;
using Object = UnityEngine.Object;

public class finsh : MonoBehaviour
{
     //public設置為unity界面配置
    public RectTransform content;
    public GameObject table;
    public GameObject tableDemo;
    private string file1 = "Assets/finsh/cc.xlsx";//讀取的文件的路徑

  
      //根據讀取Excel表格的數量通過克隆創建對應的表格
    public void CloneForm()
    {
        Dictionary<string, string> dictionary = LoadInfo(file1);
        foreach (var i in dictionary)
        {
            content = table.GetComponent<RectTransform>();
            var task = Instantiate(tableDemo, content);
            task.gameObject.SetActive(true);
            task.GetComponent<InputField>().text = i.Value;
        }
    }
    
     //讀取加載
    public void read()
    {
        GameObject.Find("table").AddComponent<finsh>().LoadInfo(file1);
        print(file1);
        CloneForm();
    }

    //找到並讀取Excel,轉換成DataSet型變量
    DataSet ReadExcel(string path)
    {
        Debug.Log(path + "read");
        FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
        IExcelDataReader iExcelDR = ExcelReaderFactory.CreateOpenXmlReader(fs);
        DataSet ds = iExcelDR.AsDataSet();
        fs.Close();
        return ds;
    }

    //加載記錄表中信息
    public Dictionary<string, string> LoadInfo(string path)
    {
        Debug.Log(path+"load");
        Dictionary<string, string> table_list=new Dictionary<string, string>();
       DataSet ds = ReadExcel(path);
        int num= ds.Tables.Count;  //查詢文件有幾個表
        print(""+num);
        int columns = ds.Tables[1].Columns.Count; //總列數,Tables[0]為待查詢的表1
        int rows = ds.Tables[1].Rows.Count; //總行數
        GetComponent<GridLayoutGroup>().constraintCount = columns;
        print(rows + "---" + columns);
        for (int j = 0; j < rows; j++)
        {
            for (int i = 0; i < columns; i++)
            {
                //讀取表1的第i行第j列
                string value = ds.Tables[1].Rows[j][i].ToString(); //ds.Tables[0].Rows[i][0]是Object,需強行轉換為string
                string key = (j + 1) + "" + (i + 1) + "";
                table_list.Add(key,value);
               // Debug.Log(key + "===" + value);

            }

           
        }

        return table_list;
    }
    
}

/*創建對象
 private Object CreateSprite(int r, int c)
{
    GameObject go=new GameObject(r.ToString()+c.ToString());
    go.AddComponent<InputField>();
    go.transform.SetParent(this.transform,false);
    return go;
    print(this.transform.name);
}*/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM