Unity3D研究院之MAC&Windows跨平臺解析Excel
阿新 • • 發佈:2018-12-19
轉載註明出處:http://www.xuanyusong.com/archives/2429
Excel 和 ICSharpCode.SharpZipLib 是第三方開發包(後面我會附帶下載地址的), 這個兩個東西必須存在。這個開發包是跨平臺的,並且完全獨立不依賴微軟的那一套東東。即時你的電腦中沒有安裝Excel也同樣是可以很好的解析
通過程式碼來解析UserLevel.xlsx
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.IO; using Excel; using System.Data; public class NewBehaviourScript : MonoBehaviour { void Start () { XLSX(); } void XLSX() { //FileStream stream = File.Open(Application.dataPath + "/UserLevel.xlsx", FileMode.Open, FileAccess.Read); //IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //DataSet result = excelReader.AsDataSet(); //int columns = result.Tables[0].Columns.Count; //int rows = result.Tables[0].Rows.Count; //for(int i = 0; i< rows; i++) //{ // for(int j =0; j < columns; j++) // { // string nvalue = result.Tables[0].Rows[i][j].ToString(); // Debug.Log(nvalue); // } //} FileStream stream = File.Open(Application.dataPath + "/UserLevel1.xlsx", FileMode.Open, FileAccess.Read); IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); do{ // sheet name Debug.Log(excelReader.Name); while (excelReader.Read()) { for (int i = 0; i < excelReader.FieldCount; i++) { string value = excelReader.IsDBNull(i) ? "" : excelReader.GetString(i); Debug.Log(value); } } }while(excelReader.NextResult()); } }
result.Tables[0].Rows.Count;
這裡0表示第一個sheet, 如果你有多個sheet的話,可以寫sheet的名子
result.Tables[“mySheet”].Rows.Count;
http://exceldatareader.codeplex.com/ 也可以在這裡查閱詳細的文件
本文下載地址: http://vdisk.weibo.com/s/qDm4IY-Ht09-
另:
ExcelPackage是一個在服務端生成Excel 2007 電子表格的Library. 下面的程式碼是生成XLSX檔案示例:
FileInfo XLSXFile = new FileInfo(XLSXFileName); using (ExcelPackage xlPackage = new ExcelPackage(XLSXFile)) { ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("Sheet1"); int row = 1; foreach (DataRow dr in dataTable.Rows) { int col = 1; foreach (object o in dr.ItemArray) { worksheet.Cell(row, col++).Value = o.ToString().Trim(); } row++; } xlPackage.Save(); }