前言
讀寫excel是遊戲開發中經常用到的技術,程序可以使用策劃、文案寫好的excel對數據進行修改,達到簡易配合的目的。今天記錄一下對Excel的讀寫過程。
準備
下圖是所需類庫。Excel.dll、EPPlus.dll、ICSharpCode.SharpZLib.dll在網上可以搜到。
備註:
1.你的unity版本是多少,去對應的安裝目錄中取dll
2.System.Data.dll 在D:\Program Files\Unity2017.2\Editor\Data\Mono\lib\mono\2.0
3.I18N開頭的dll 在 D:\Program Files\Unity2017.2\Editor\Data\Mono\lib\mono\unity
1.讀取excel
需要注意讀取excel默認第一行第一列是索引0開始,寫入是索引1開始。另外要using System.Data使用DateSet儲存excel數據。這裏0表示第一個sheet, 如果你有多個sheet的話,可以寫sheet的名字,例如result.Tables[“mySheet”].Rows.Count
代碼示例:
FileStream stream = File.Open(Application.dataPath + "/Excels/鬼船新攻略文字.xlsx", FileMode.Open, FileAccess.Read); //讀取文件流
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //讀取Excel
DataSet result = excelReader.AsDataSet(); //儲存數據
//int columns = result.Tables[0].Columns.Count; //列數 0開始
int rows = result.Tables[0].Rows.Count; //行數
//驗證數據長度是否匹配 這個根據具體項目取捨
if(rows != TipsInfoController.instance.allTips.Count)
{
Debug.LogError("數據長度不匹配!加載失敗!");
return;
}
for (int i = 0; i < rows; i++)
{
string nvalue = result.Tables[0].Rows[i][1].ToString();
TipsInfoController.instance.allTips[i].text.中文 = nvalue; //寫入 根據具體項目自己改動
EditorUtility.SetDirty(TipsInfoController.instance.allTips[i]); //Unity中保存
}
2.寫入Excel
需要using OfficeOpenXml
Epplus備註:
教程及常用設置
代碼示例:
static readonly string _filePath = Application.dataPath + "/Excels/對話.xlsx"; //存儲位置
static readonly string _sheetName = "Sheet1"; //表格名稱
public static void ReadTalks()
{
FileInfo _excelName = new FileInfo(_filePath);
if (_excelName.Exists)
{
//刪除舊文件,並創建一個新的 excel 文件。
_excelName.Delete();
_excelName = new FileInfo(_filePath);
}
//通過ExcelPackage打開文件
using (ExcelPackage package = new ExcelPackage(_excelName))
{
//在 excel 空文件添加新 sheet,並設置名稱。
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(_sheetName);
//添加列名
worksheet.Cells[1, 1].Value = "ID(對話名稱)";
worksheet.Cells[1, 2].Value = "立繪(文件名,不顯示則不填)";
worksheet.Cells[1, 3].Value = "名字";
worksheet.Cells[1, 4].Value = "對話內容(對話順序以先後順序排序)";
int whichRow = 2;//第一行已經寫好了,所以從第二行開始
// 讀取數據的長度,這個根據自己項目改動
for (int i = 0; i < ScriptData.instance.talkList.Length; i++)
{
for (int j = 0; j < ScriptData.instance.talkList[i].talkList.Count; j++)//寫入
{
if(ScriptData.instance.talkList[i].name != null)
worksheet.Cells[whichRow, 1].Value = ScriptData.instance.talkList[i].name;
if (ScriptData.instance.talkList[i].talkList[j].Image != null)
worksheet.Cells[whichRow, 2].Value = ScriptData.instance.talkList[i].talkList[j].Image.name;
if (ScriptData.instance.talkList[i].talkList[j].Name != null)
worksheet.Cells[whichRow, 3].Value = ScriptData.instance.talkList[i].talkList[j].Name.Text;
if (ScriptData.instance.talkList[i].talkList[j].Text != null)
worksheet.Cells[whichRow, 4].Value = ScriptData.instance.talkList[i].talkList[j].Text.Text;
whichRow += 1;
}
whichRow += 1;
}
package.Save(); //儲存
}