分享一個讀取excel的方法。
只可以再unityeditor編輯下使用
不做太多的解釋,直接上代碼,每個方法都有註釋。
有任何問題直接留言,看到會回覆 QQ791719266 備註“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;
//可增加
}