1. 程式人生 > >Unity 讀取 Excel 表格 配置 遊戲 引數

Unity 讀取 Excel 表格 配置 遊戲 引數

在做遊戲時,經常會遇到需要讀取Excel表格,用來配置遊戲資料,供策化除錯程式用

這裡Down了三種方法,都採用第三方庫,不需要安裝Office,關鍵free
第一種:NPOI

讀取程式碼:

/// <summary>    /// 將excel中的資料匯入到DataTable中
/// </summary>
/// <param name="fileName">excel檔案的名稱</param>
/// <param name="sheetName">excel工作薄sheet的名稱</param>
/// <param name="isFirstRowColumn">第一行是否是屬性</param>
/// <returns>返回的DataTable</returns>
public DataTable ReadExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
{
    if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(sheetName)) return null;
    DataTable dataTable = null;
    DataColumn column = null;
    DataRow dataRow = null;
    IWorkbook workBook = null;
    IRow row = null;
    ICell cell = null;
    int startRow = 0;
    try
    {
        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            if (fileName.ToLower().EndsWith(".xlsx")) //2007版本以上
                workBook = new XSSFWorkbook(fs);
            else if (fileName.ToLower().EndsWith(".xls")) //2003版本
                workBook = new HSSFWorkbook(fs);
 
            if (workBook != null)
            {
                ISheet sheet = workBook.GetSheet(sheetName); //讀取第一個sheet,當然也可以迴圈讀取每個sheet  
                dataTable = new DataTable();
                if (sheet != null)
                {
                    int rowCount = sheet.LastRowNum; //總行數  
                    if (rowCount > 0)
                    {
                        IRow firstRow = sheet.GetRow(0); //第一行  
                        int cellCount = firstRow.LastCellNum; //列數  
 
                        //構建datatable的列  
                        if (isFirstRowColumn)
                        {
                            startRow = 1; //如果第一行是列名,則從第二行開始讀取  
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                            {
                                cell = firstRow.GetCell(i);
                                if (cell != null)
                                {
                                    if (cell.StringCellValue != null)
                                    {
                                        column = new DataColumn(cell.StringCellValue);
                                        dataTable.Columns.Add(column);
                                    }
                                }
                            }
                        }
                        else
                        {
                            for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                            {
                                column = new DataColumn("column" + (i + 1));
                                dataTable.Columns.Add(column);
                            }
                        }
 
                        //填充行  
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            row = sheet.GetRow(i);
                            if (row == null) continue;
 
                            dataRow = dataTable.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                cell = row.GetCell(j);
                                if (cell == null)
                                {
                                    dataRow[j] = "";
                                }
                                else
                                {
                                    //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                    switch (cell.CellType)
                                    {
                                        case CellType.Blank:
                                            dataRow[j] = "";
                                            break;
                                        case CellType.Numeric:
                                            short format = cell.CellStyle.DataFormat;
                                            //對時間格式(2015.12.5、2015/12/5、2015-12-5等)的處理  
                                            if (format == 14 || format == 31 || format == 57 || format == 58)
                                                dataRow[j] = cell.DateCellValue;
                                            else
                                                dataRow[j] = cell.NumericCellValue;
                                            break;
                                        case CellType.String:
                                            dataRow[j] = cell.StringCellValue;
                                            break;
                                    }
                                }
                            }
                            dataTable.Rows.Add(dataRow);
                        }
                    }
                }
            }
            fs.Close();
            fs.Dispose();
        }
        return dataTable;
    }
    catch (Exception ex)
    {
        LogHelper.WriteLog(ex);
        return null;
    }
}

第二種:Excel.dll 

讀取程式碼:

/// <summary>    /// 將excel中的資料匯入到DataTable中
/// </summary>
/// <param name="fileName">excel檔案的名稱</param>
/// <param name="sheetName">excel工作薄sheet的名稱</param>
/// <returns>返回的DataTable</returns>
public DataTable ReadExcelToDataTable(string fileName, string sheetName)
{
    if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(sheetName)) return null;
    IExcelDataReader excelReader = null;
 
    try
    {
        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            if (fileName.ToLower().EndsWith(".xlsx"))
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
            else if (fileName.ToLower().EndsWith(".xls"))
                excelReader = ExcelReaderFactory.CreateBinaryReader(fs);
 
            if (excelReader == null) return null;
            DataSet result = excelReader.AsDataSet();
 
            fs.Close();
            fs.Dispose();
            excelReader.Close();
 
            return result.Tables[sheetName];
        }
    }
    catch (Exception ex)
    {
        LogHelper.WriteLog(ex);
        return null;
    }
}

第三種:EPPlus 推薦此方法,具體請自己用Excel測試

呼叫程式碼:
/// <summary>    /// 將excel中的資料匯入到DataTable中
/// </summary>
/// <param name="fileName">excel檔案的名稱</param>
/// <param name="sheetName">excel工作薄sheet的名稱</param>
/// <param name="isFirstRowColumn">第一行是否是屬性</param>
/// <returns>返回的DataTable</returns>
public DataTable ReadExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
{
    if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(sheetName)) return null;
    try
    {
        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            var package = new ExcelPackage(fs);
            DataTable data = new DataTable();
 
            ExcelWorkbook workBook = package.Workbook;
            if (workBook != null)
            {
                if (workBook.Worksheets.Count > 0) 
                {
                    ExcelWorksheet currentWorksheet = workBook.Worksheets[sheetName];
 
                    int lastRow = currentWorksheet.Dimension.End.Row;
                    int lastColumn = currentWorksheet.Dimension.End.Column;
 
                    int columnCount = 1;
                    while (columnCount <= lastColumn)
                    {
                        data.Columns.Add(Convert.ToString(currentWorksheet.Cells[1, columnCount].Value));
                        columnCount++;
                    }
 
                    int rowCount = 0;
                    if (isFirstRowColumn) rowCount = currentWorksheet.Dimension.Start.Row + 1;
                    else rowCount = currentWorksheet.Dimension.Start.Row;
 
                    while (rowCount <= lastRow)
                    {
                        columnCount = 1;
                        DataRow newRow = data.NewRow();
                        while (columnCount <= lastColumn)
                        {
                            newRow[data.Columns[columnCount - 1]] =
                                Convert.ToString(currentWorksheet.Cells[rowCount, columnCount].Value);
                            columnCount++;
                        }
                        rowCount++;
                        data.Rows.Add(newRow);
                    }
                }
                fs.Close();
                fs.Dispose();
            }
            return data;
        }
    }
    catch (Exception ex)
    {
        LogHelper.WriteLog(ex);
        return null;
    }
}