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("数量==" + 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);
}
/// 
/// 读
/// 
[MenuItem("Excel4Unity/Test/Read")] 
static void Read()
{
    string path = Application.dataPath + "/Test/Test3.xlsx";
    Excel xls =  ExcelHelper.LoadExcel(path);
    xls.ShowLog();
}
/// 
/// 新建一张excel表,覆盖了原来的表(没有这张表就创建一下)
/// 
[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);
}
/// 
/// 把.xlsx根据写好的格式转换成.cs  
/// 这里设置.xlsx的第一行为字段名字 ed.FieldNameLine = 1;
/// 这里设置.xlsx的第二行为字段类型 ed.FieldTypeLine = 2;
/// 这里设置.xlsx的第三行为字段值   ed.FieldValueLine = 3;
/// 这里设置如果字段名字为空或者类型为空或者字段名字以#为开头则不添加该字段,ed.IgnoreSymbol = "#";#为忽略值
/// 
[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();
}
/// 
/// 解析excel文件在这里 for (int i = 4; i < = table.NumberOfRows; i++)写死了从第四行开始
/// 
/// 
/// 
/// 
/// 
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 = "解析错误! \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;
///


/// 此为生成的类
///

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 () {
    //拿到测试类对象
    testItem = new TestItem();
    //加载写好的json
    Object obj= Resources.Load("DataFiles/Test4") ;
    //把加载的数据转为string
    string str = obj.ToString();
    Debug.Log("str==" + str);
    //new一个jsondata
    JsonData data = new JsonData();
    //把加载的字符串转换成obj给data
    data = JsonMapper.ToObject(str);
    Debug.Log("data==" + data["Test"][0]);
    //调用setup函数给测试类字段赋值
    testItem.Setup(data["Test"][0]);
    Debug.Log("ID==" + testItem.ID);
    //Debug.Log(data[0]);
}

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

}

你可能感兴趣的:(Excel4Unity-master插件使用)