Excel4Unity-master插件使用

using UnityEngine;
using UnityEditor;
using System.Collections;
using OfficeOpenXml;
using System.IO;
using System.Collections.Generic;
using LitJson;
using System.Text;

public class Excel4Unity : Editor
{

[MenuItem("Excel4Unity/Test/ReadWrite")] 
static void ReadWrite()
{
    Excel xls = new Excel();
    ExcelTable table = new ExcelTable();
    table.TableName = "test";
    string outputPath = Application.dataPath + "/Test/Test2.xlsx";
    xls.Tables.Add(table);
    Debug.Log("數(shù)量==" + xls.Tables.Count);
    xls.Tables[0].SetValue(1, 1, "1");
    xls.Tables[0].SetValue(1, 2, "2");
    xls.Tables[0].SetValue(2, 1, "3");
    xls.Tables[0].SetValue(2, 2, "4");
    xls.ShowLog();
    ExcelHelper.SaveExcel(xls, outputPath);
}
/// <summary>
/// 讀
/// </summary>
[MenuItem("Excel4Unity/Test/Read")] 
static void Read()
{
    string path = Application.dataPath + "/Test/Test3.xlsx";
    Excel xls =  ExcelHelper.LoadExcel(path);
    xls.ShowLog();
}
/// <summary>
/// 新建一張excel表,覆蓋了原來(lái)的表(沒有這張表就創(chuàng)建一下)
/// </summary>
[MenuItem("Excel4Unity/Test/Write")] 
static void Write()
{
    Excel xls = new Excel();
    ExcelTable table = new ExcelTable();
    table.TableName = "test";
    string outputPath = Application.dataPath + "/Test/Test5.xlsx";
    xls.Tables.Add(table);
    xls.Tables[0].SetValue(1, 1, Random.Range(1000,100000).ToString());
    xls.ShowLog();
    ExcelHelper.SaveExcel(xls, outputPath);
}
/// <summary>
/// 把.xlsx根據(jù)寫好的格式轉(zhuǎn)換成.cs  
/// 這里設(shè)置.xlsx的第一行為字段名字 ed.FieldNameLine = 1;
/// 這里設(shè)置.xlsx的第二行為字段類型 ed.FieldTypeLine = 2;
/// 這里設(shè)置.xlsx的第三行為字段值   ed.FieldValueLine = 3;
/// 這里設(shè)置如果字段名字為空或者類型為空或者字段名字以#為開頭則不添加該字段锰霜,ed.IgnoreSymbol = "#";#為忽略值
/// </summary>
[MenuItem("Excel4Unity/Test/GenerateModel")] 
static void GenerateModel()
{
    string path = Application.dataPath + "/Test/Test4.xlsx";
    Excel xls =  ExcelHelper.LoadExcel(path);
    ExcelDeserializer ed = new ExcelDeserializer();
    ed.FieldNameLine = 1;
    ed.FieldTypeLine = 2;
    ed.FieldValueLine = 3;
    ed.IgnoreSymbol = "#";
    ed.ModelPath = Application.dataPath + "/Editor/Excel4Unity/DataItem.txt";
    ed.GenerateCS(xls.Tables[1]);
}

[MenuItem(@"Excel4Unity/Test/Excel2JSON")]
static void Excel2JSON()
{
    Object[] objs = Selection.objects;
    for (int i = 0; i < objs.Length; i++)
    {
        string path = AssetDatabase.GetAssetPath(objs[i]);
        if (path.EndsWith(".xlsx"))
        {
            Excel4Unity.ParseFile(path);
        }
        else
        {
            EditorUtility.DisplayDialog("提示", "暫不支持的文件格式" + path, "ok");
            return;
        }
    }
    AssetDatabase.Refresh();
}
/// <summary>
/// 解析excel文件在這里 for (int i = 4; i < = table.NumberOfRows; i++)寫死了從第四行開始
/// </summary>
/// <param name="path"></param>
/// <param name="createCS"></param>
/// <param name="isMac"></param>
/// <returns></returns>
public static string ParseFile(string path, bool createCS = true, bool isMac = false)
{
    //      UnityEngine.Debug.LogError ("path " + path);
    if (!path.EndsWith("xlsx"))
    {
        return null;
    }

    string tableName = "";
    string currentPropName = "";
    int tableRow = 0;
    int tableColumn = 0;
    string v = "";
    Excel excel = null;
    excel = ExcelHelper.LoadExcel(path);
    try
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        JsonWriter writer = new JsonWriter(sb);
        writer.WriteObjectStart();
        foreach (ExcelTable table in excel.Tables)
        {
            tableName = table.TableName;
            bool language = tableName.ToLower().Contains("language");
            if (table.TableName.StartsWith("#"))
            {
                continue;
            }
            if (createCS)
            {
                ExcelDeserializer ed = new ExcelDeserializer();
                ed.FieldNameLine = 1;
                ed.FieldTypeLine = 2;
                ed.FieldValueLine = 3;
                ed.IgnoreSymbol = "#";
                ed.ModelPath = Application.dataPath + "/Editor/Excel4Unity/DataItem.txt";
                ed.GenerateCS(table);
            }
            writer.WritePropertyName(table.TableName);
            writer.WriteArrayStart();
            //這里寫死了從excel的第四行開始解析
            for (int i = 4; i <= table.NumberOfRows; i++)
            {
                tableRow = i;
                string idStr = table.GetValue(i, 1).ToString();
                if (idStr.Length <= 0)
                {
                    //                      UnityEngine.Debug.LogError ("ID error:" + tableName + "  (第" + i + "行)");
                    break;
                }
                writer.WriteObjectStart();

                for (int j = 1; j <= table.NumberOfColumns; j++)
                {
                    tableColumn = j;
                    string propName = table.GetValue(1, j).ToString();
                    string propType = table.GetValue(3, j).ToString();
                    propName = propName.Replace("*", "");
                    currentPropName = propName;

                    if (propName.StartsWith("#"))
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(propName) || string.IsNullOrEmpty(propType))
                    {
                        continue;
                    }
                    writer.WritePropertyName(propName);
                    v = table.GetValue(i, j).ToString();
                    if (propType.Equals("int"))
                    {
                        int value = v.Length > 0 ? int.Parse(v) : 0;
                        writer.Write(value);
                    }
                    else if (propType.Equals("bool"))
                    {
                        int value = v.Length > 0 ? int.Parse(v) : 0;
                        writer.Write(value);
                    }
                    else if (propType.Equals("float"))
                    {
                        float value = v.Length > 0 ? float.Parse(v) : 0;
                        writer.Write(value);
                    }
                    else
                    {
                        string ss = table.GetValue(i, j).ToString();
                        if (language && ss.Contains(" "))
                        {
                            ss = ss.Replace(" ", "\u00A0");
                        }
                        writer.Write(ss);
                    }
                }
                writer.WriteObjectEnd();
            }
            writer.WriteArrayEnd();
        }
        writer.WriteObjectEnd();
        string outputDir = Application.dataPath + "/Resources/DataFiles/";
        string outputPath = outputDir + Path.GetFileNameWithoutExtension(path) + ".txt";
        if (!Directory.Exists(outputDir)) {
            Directory.CreateDirectory(outputDir);
        }
        string str = string.Empty;
        if (File.Exists(path))
        {
            byte[] bytes = File.ReadAllBytes(path);
            UTF8Encoding encoding = new UTF8Encoding();
            str = encoding.GetString(bytes);
        }
        string content = sb.ToString();
        if (str != content)
        {
            File.WriteAllText(outputPath, content);
        }
        Debug.Log("convert success! path = " + path);

        return sb.ToString();
    }
    catch (System.Exception e)
    {
        if (excel == null)
        {
            //                EditorUtility.DisplayDialog("ERROR!", "open excel failed!","ok"); 
            UnityEngine.Debug.LogError("open excel failed!");
        }
        else
        {
            string msg = "解析錯(cuò)誤! \n表:" + tableName + " \n字段:" + currentPropName + "  \n第" + tableRow + "行,第" + tableColumn + "列 \nvalue = " + v;
            EditorUtility.DisplayDialog("error!", msg, "ok");
            UnityEngine.Debug.LogError(e);
            UnityEngine.Debug.LogError(e.StackTrace);
            UnityEngine.Debug.LogError(msg);
        }
        UnityEngine.Debug.LogError(e.StackTrace.ToString());
        return null;
    }
}

}

using UnityEngine;
using System.Collections;
using LitJson;
/// <summary>
/// 此為生成的類
/// </summary>
public class TestItem : DataItem {
public int ID;
public override int Identity(){ return ID; }
public string Name;
public int Type;

public override void Setup(JsonData data) {
    base.Setup(data);
    ID = int.Parse(data["ID"].ToString());
    Name = data["Name"].ToString();
    Type = int.Parse(data["Type"].ToString());

}

public TestItem () {

}

}


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
public class TestExcel2Json : MonoBehaviour {

TestItem testItem;



// Use this for initialization
void Start () {
    //拿到測(cè)試類對(duì)象
    testItem = new TestItem();
    //加載寫好的json
    Object obj= Resources.Load("DataFiles/Test4") ;
    //把加載的數(shù)據(jù)轉(zhuǎn)為string
    string str = obj.ToString();
    Debug.Log("str==" + str);
    //new一個(gè)jsondata
    JsonData data = new JsonData();
    //把加載的字符串轉(zhuǎn)換成obj給data
    data = JsonMapper.ToObject(str);
    Debug.Log("data==" + data["Test"][0]);
    //調(diào)用setup函數(shù)給測(cè)試類字段賦值
    testItem.Setup(data["Test"][0]);
    Debug.Log("ID==" + testItem.ID);
    //Debug.Log(data[0]);
}

// Update is called once per frame
void Update () {
    
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市鸳兽,隨后出現(xiàn)的幾起案子亦渗,更是在濱河造成了極大的恐慌献联,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件哨鸭,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡娇妓,警方通過查閱死者的電腦和手機(jī)像鸡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)哈恰,“玉大人只估,你說我怎么就攤上這事志群。” “怎么了蛔钙?”我有些...
    開封第一講書人閱讀 168,017評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵锌云,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我吁脱,道長(zhǎng)宾抓,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評(píng)論 1 296
  • 正文 為了忘掉前任豫喧,我火速辦了婚禮石洗,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘紧显。我一直安慰自己讲衫,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評(píng)論 6 397
  • 文/花漫 我一把揭開白布孵班。 她就那樣靜靜地躺著涉兽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪篙程。 梳的紋絲不亂的頭發(fā)上枷畏,一...
    開封第一講書人閱讀 52,255評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音虱饿,去河邊找鬼拥诡。 笑死,一個(gè)胖子當(dāng)著我的面吹牛氮发,可吹牛的內(nèi)容都是我干的渴肉。 我是一名探鬼主播,決...
    沈念sama閱讀 40,825評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼爽冕,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼仇祭!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起颈畸,我...
    開封第一講書人閱讀 39,729評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤乌奇,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后眯娱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體礁苗,經(jīng)...
    沈念sama閱讀 46,271評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評(píng)論 3 340
  • 正文 我和宋清朗相戀三年困乒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了寂屏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,498評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖迁霎,靈堂內(nèi)的尸體忽然破棺而出吱抚,到底是詐尸還是另有隱情,我是刑警寧澤考廉,帶...
    沈念sama閱讀 36,183評(píng)論 5 350
  • 正文 年R本政府宣布秘豹,位于F島的核電站,受9級(jí)特大地震影響昌粤,放射性物質(zhì)發(fā)生泄漏既绕。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評(píng)論 3 333
  • 文/蒙蒙 一涮坐、第九天 我趴在偏房一處隱蔽的房頂上張望凄贩。 院中可真熱鬧,春花似錦袱讹、人聲如沸疲扎。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)椒丧。三九已至,卻和暖如春救巷,著一層夾襖步出監(jiān)牢的瞬間壶熏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工浦译, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留棒假,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,906評(píng)論 3 376
  • 正文 我出身青樓管怠,卻偏偏與公主長(zhǎng)得像淆衷,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子渤弛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容