Unity Excel 文件讀取和寫入

在網上看到不少Unity 的解析Excel 的文章,其中最經典的一篇莫過於雨凇Momo的Unity3D研究院之MAC&Windows跨平臺解析Excel(六十五)git

可是在使用的過程當中仍是碰到了很多的問題,在這裏總結一下,但願能對看到此處的朋友一個幫助。數組

Excel的讀取,編輯器

須要加入庫文件 Excel.dll 和ICSharpCode.SharpZipLib庫文件,官方連接 http://exceldatareader.codeplex.com/ui

[csharp] view plain copy.net

using Excel;
using System.Data;

Excel文件讀取和轉換List格式指針

[csharp] view plain copyexcel

public class ExcelAccess

{

public static string ExcelName = "Book.xlsx";

public static string[] SheetNames = { "sheet1", "sheet2", "sheet3", "sheet4" };

public static List

SelectMenuTable(int tableId)


{

DataRowCollection collect = ExcelAccess.ReadExcel(SheetNames[tableId - 1]);

List

menuArray = new List();


for (int i = 1; i < collect.Count; i++)

{

if (collect[i][1].ToString() == "") continue;

Menu menu = new Menu();

menu.m_Id = collect[i][0].ToString();

menu.m_level = collect[i][1].ToString();

menu.m_parentId = collect[i][2].ToString();

menu.m_name = collect[i][3].ToString();

menuArray.Add(menu);

}

return menuArray;

}

///



/// 讀取 Excel 須要添加 Excel; System.Data;

///

///

///

static DataRowCollection ReadExcel(string sheet)

{

FileStream stream = File.Open(FilePath(ExcelName), FileMode.Open, FileAccess.Read, FileShare.Read);

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

DataSet result = excelReader.AsDataSet();

//int columns = result.Tables[0].Columns.Count;

//int rows = result.Tables[0].Rows.Count;

return result.Tables[sheet].Rows;

}

}

 

這裏邏輯很簡單,若是有不懂得能夠上Excel的文檔裏去看,可是這個Excel的庫有一個限制,就是隻能讀不能寫,而且只能在編輯器下用,若是打包出來加載時會報空指針異常,緣由就不清楚了,因此建議你們,讓策劃把Excel寫好後,在編輯器下讀取後用Unity 的ScriptableObject 存起來,而後保存成Asset文件,能夠在運行時更方便的讀取。code

 

下面給出個人實現方式,你們能夠根據本身實體類來寫這個StrignHolder;blog

 

StringHolder類ip

 

[csharp] view plain copy

 

using UnityEngine;

using System.Collections.Generic;

public class BookElementHolder : ScriptableObject

{

public List

menus1;


public List

menus2;


public List

menus3;


public List goods;

}

 

製做Asset編輯器(能夠把Asset達成AssetBundle的包,而後用WWW讀取)

 

[csharp] view plain copy

[MenuItem("Assetbundles/Create Assetbundles")]

public static void ExcuteBuild()

{

BookElementHolder holder = ScriptableObject.CreateInstance();

holder.menus1 = ExcelAccess.SelectMenuTable(1);

holder.menus2 = ExcelAccess.SelectMenuTable(2);

holder.menus3 = ExcelAccess.SelectMenuTable(3);

holder.goods = ExcelAccess.SelectGoodTable();

AssetDatabase.CreateAsset(holder, HolderPath);

AssetImporter import = AssetImporter.GetAtPath(HolderPath);

import.assetBundleName = "booknames";

BuildPipeline.BuildAssetBundles("Assets/Abs");

Debug.Log("BuildAsset Success!");

}

Asset讀取方式

 

[csharp] view plain copy

public string assetName = "bonenames";
public void readAsset()
{
Object asset = Resources.Load(assetName);
BookElementHolder ceh = (BookElementHolder)asset;
foreach (Good gd in ceh.goods)
{
Debug.Log(gd.m_name);
}
}

好了,Excel的讀取就到這裏,接下來說一下Excel 的寫入,怎麼生成一個Excel文件,並把數組或字典中的數據寫入Excel中呢?

 

此時須要一個Excel.dll的姐妹,EPPlus.dll 官方連接 https://epplus.codeplex.com/releases/view/118053

 

使用方法在官方的文檔中都有,這裏只貼出個人實現方式。

 

須要添加的命名空間

 

[csharp] view plain copy

using OfficeOpenXml;

寫入方法

 

[csharp] view plain copy​​​​​​​

public static void WriteExcel(string outputDir)

{

//string outputDir = EditorUtility.SaveFilePanel("Save Excel", "", "New Resource", "xlsx");

FileInfo newFile = new FileInfo(outputDir);

if (newFile.Exists)

{

newFile.Delete(); // ensures we create a new workbook

newFile = new FileInfo(outputDir);

}

using (ExcelPackage package = new ExcelPackage(newFile))

{

// add a new worksheet to the empty workbook

ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");

//Add the headers

worksheet.Cells[1, 1].Value = "ID";

worksheet.Cells[1, 2].Value = "Product";

worksheet.Cells[1, 3].Value = "Quantity";

worksheet.Cells[1, 4].Value = "Price";

worksheet.Cells[1, 5].Value = "Value";

//Add some items…

worksheet.Cells["A2"].Value = 12001;

worksheet.Cells["B2"].Value = "Nails";

worksheet.Cells["C2"].Value = 37;

worksheet.Cells["D2"].Value = 3.99;

worksheet.Cells["A3"].Value = 12002;

worksheet.Cells["B3"].Value = "Hammer";

worksheet.Cells["C3"].Value = 5;

worksheet.Cells["D3"].Value = 12.10;

worksheet.Cells["A4"].Value = 12003;

worksheet.Cells["B4"].Value = "Saw";

worksheet.Cells["C4"].Value = 12;

worksheet.Cells["D4"].Value = 15.37;

//save our new workbook and we are done!

package.Save();

}

}

把上面的數據換成你本身的數組和字典遍歷就OK 了。好了,今天的課程就到這裏,歡迎大神指教啊

 

因爲你們遇到問題較多,特附上工程地址:

Git地址:https://git.oschina.net/passionyu/ExcelReadWrite.git

相關文章
相關標籤/搜索