unity 分享一个读取excel踩坑的方法,只限于unityeditor状态下。

分享一个读取excel的方法。

只可以再unityeditor编辑下使用

不做太多的解释,直接上代码,每个方法都有注释。

有任何问题直接留言,看到会回复 QQ群 207019099 备注“CSDN 读取excel”

资源路径如下图所示。下面会放litjson、excel动态库链接。
资源如下
倒数第二个是litjson,用于转换json格式的,需要的用,不需要的就不用搭理了

litjson资源链接 :https://pan.baidu.com/s/1h6TUfNwcoo0G5kr0Fvf5xg 密码:fi33

前两个dll链接:https://pan.baidu.com/s/1OHx-l_-PBjn-tTyBDriXKA 密码:v1pb

System.Data为本机安装版本的数据文件,路径为Editor\Data\Mono\lib\mono\unity

using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using UnityEngine;
using LitJson;
using UnityEditor;
public class ReadExcel
{
    public static List<RadarInfo> radarInfoList = new List<RadarInfo>();

    [MenuItem("GF/ReadExcel/ToJson")]
    public static void ReadExcelToJson()
    {
        GameReadExcel(Application.streamingAssetsPath + "/excel/20160602RadarInfo.xlsx");
    }

    /// <summary>
    /// 只读Excel方法
    /// </summary>
    /// <param name="ExcelPath"></param>
    /// <returns></returns>
    public static void GameReadExcel(string ExcelPath)
    {
        FileStream stream = File.Open(ExcelPath, FileMode.Open, FileAccess.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

        DataSet result = excelReader.AsDataSet();

        int rows = result.Tables[0].Rows.Count;//获取行数
        int columns = result.Tables[0].Columns.Count;//获取列数

        RadarInfo radarinfo = new RadarInfo();
        //从第二行开始读
        for (int i = 1; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                string nvalue = result.Tables[0].Rows[i][j].ToString();

                if (!String.IsNullOrEmpty(nvalue))
                {
                    if (j==0)
                    {
                        radarinfo.bm00 = nvalue;
                    }
                    else if (j == 1)
                    {
                        radarinfo.bm01 = nvalue;
                    }
                   //有多少列都可以在下面增加。有更好的方法可以告诉我,我能里有限
                    radarInfoList.Add(radarinfo);
                }
            }
        }
        //转换为json组
        string json = JsonMapper.ToJson(radarInfoList);
         //存为txt文件
        StreamWriter sw;
        FileInfo fi = new FileInfo(Application.dataPath + "/" + "json" + ".txt");

        if (!fi.Exists)
        {
            sw = fi.CreateText();
        }
        else
        {
            fi.Delete();
            sw = fi.CreateText();
        }

        sw.Write(json);
        sw.Close();
        sw.Dispose();
    }
}

public class RadarInfo
{
    public string bm00;
    public string bm01;
    public string bm02;
    //可增加
}

猜你喜欢

转载自blog.csdn.net/gaofei12300/article/details/82851380