我在unity里需要導出成Excel格式,試了一些方法,其中用c#的com組件的我還沒成功不知道該怎么在unity里調用,(如果哪位大哥用別的方法在unity里成功了,可以交流下,最好給我一個小demo(849288321@qq.com),謝謝啦.),不過后來找到了這個org.in2bits.MyXls ,需要導入這個dll(網上有很多),然后用着還挺好用,我這寫的一個小例子僅供參考,
using UnityEngine; using System.Collections; using org.in2bits.MyXls; using System.Collections.Generic; public class TestInfo { public string name; public string id; public string num; }; public class ExcelMakerManager { public static ExcelMakerManager eInstance; public static ExcelMakerManager CreateExcelMakerManager() { if(eInstance==null) { eInstance = new ExcelMakerManager(); } return eInstance; } //鏈表為 物體信息 . public void ExcelMaker(string name, List<TestInfo> listInfo) { XlsDocument xls = new XlsDocument();//新建一個xls文檔 xls.FileName = name;// @"D:\tests.xls";//設定文件名 //Add some metadata (visible from Excel under File -> Properties) xls.SummaryInformation.Author = "xyy"; //填加xls文件作者信息 xls.SummaryInformation.Subject = "test";//填加文件主題信息 string sheetName = "Sheet0"; Worksheet sheet = xls.Workbook.Worksheets.AddNamed(sheetName);//填加名為"chc 實例"的sheet頁 Cells cells = sheet.Cells;//Cells實例是sheet頁中單元格(cell)集合 int rowNum = listInfo.Count; int rowMin = 1; int row = 0; for (int x = 0; x < rowNum + 1; x++) { if (x == 0) { //根據具體的物體信息 .需要重新寫 cells.Add(1, 1, "名字"); cells.Add(1, 2, "ID"); cells.Add(1, 3, "數量"); } else { cells.Add(rowMin + x, 1, listInfo[row].id); cells.Add(rowMin + x, 2, listInfo[row].name); cells.Add(rowMin + x, 3, listInfo[row].num); row++; } } xls.Save(); } }
然后下面是調用上面的這個方法
using UnityEngine; using System.Collections; using System.IO; using org.in2bits.MyXls; using System; using System.Collections.Generic; public class test : MonoBehaviour { string path; TestInfo test1; TestInfo test2; TestInfo test3; List<TestInfo> listInfos; // Use this for initialization void Start() { ExcelMakerManager.CreateExcelMakerManager(); // --測試數據 test1 = new TestInfo(); test1.id = "one"; test1.name = "test1"; test1.num = "x"; test2 = new TestInfo(); test2.id = "two"; test2.name = "test2"; test2.num = "22"; test3 = new TestInfo(); test3.id = "tree"; test3.name = "test3"; test3.num = "333"; listInfos = new List<TestInfo>(); listInfos.Add(test1); listInfos.Add(test2); listInfos.Add(test3); // --測試數據 // ManagerExcel.CreateE(); } // Update is called once per frame void Update() { } void OnGUI() { if (GUI.Button(new Rect(100, 0, 100, 100), "aa")) { PrintExcel(); Debug.Log("aaaa"); } } public void PrintExcel() { if (!Directory.Exists(Application.dataPath + "/Prints")) { Directory.CreateDirectory(Application.dataPath + "/Prints"); } path = Application.dataPath + "/Prints/Excel_" + System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".xls"; ExcelMakerManager.eInstance.ExcelMaker(path, listInfos); } }
至於改字體啥的網上都有相應的例子.可以自己去看看...這里就不多說了.
結果如圖: