unity读取Excel

使用unity5.6的和Excel是2016版本。

新建工程,新建文件夹Plugins,然后导入两个dll,一个是EXCEL一个system.Data。

 

 

读取脚本如下:

using System.Collections.Generic;
using UnityEngine;
using System.Data;
using System.IO;
using Excel;
public class DoExcel {    

    public static DataSet ReadExcel(string path)
    {
        FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);     

        DataSet result = excelReader.AsDataSet();
        excelReader.Close();
        return result;

    }

    public static List<string> Load(string path)
    {
      
        DataSet resultds = ReadExcel(path);
        int column = resultds.Tables[0].Columns.Count;
        int row = resultds.Tables[0].Rows.Count;

        Debug.Log("总行数:" + row+"  总列数:" +column);     

        List<string> saveall = new List<string>();  

        //获得每行的名字,并添加到数组里
        for (int i=1;i< row; i++)
        {          
            string getnames;
            getnames = resultds.Tables[0].Rows[i][1].ToString();           
            Debug.Log("第"+i+"行:" + getnames.ToString());
            saveall.Add(getnames.ToString());

        }

        return saveall;
    }

}



只要调用上面代码里的Load(string path)方法就可以。

把要读取的Excel的路径作为参数传入即可。如下:

void Start()
    {

        string ak = System.Environment.CurrentDirectory;
        print(ak);
        //savename = DoExcel.Load(Application.dataPath + "\\Data\\" + "yg.xlsx");
        savename = DoExcel.Load(ak + "\\yg.xlsx");
        
        allsavedvalue = savename.Count;
    }

在当前文件目录下存在名为yg的Excel表格

然后运行unity即可看到数据已经读取完成,输出了log

-------------注意一点,yg这个Excel表格里的第一行必须是string类型的--------如下:

如果第一行不是string会出现如下错误:就说类型是无法转化的。

 

### 实现 Unity读取 Excel 文件 在 Unity读取 Excel 文件并非直接支持的功能,但可以借助第三方库或插件完成此操作。以下是几种常见的方式: #### 方法一:使用 CSV 替代 Excel 一种简单的方法是将 Excel 文件另存为 CSV 格式,在 Unity 中解析 CSV 文件相对容易得多。 ```csharp using System; using System.IO; public class CsvReader { public static string[] ReadCsv(string filePath) { var lines = File.ReadAllLines(filePath); var result = new string[lines.Length][]; for (int i = 0; i < lines.Length; ++i) { result[i] = lines[i].Split(','); } return result; } } ``` 这种方法适用于不需要复杂格式的数据表单[^1]。 #### 方法二:利用 NPOI 库读取 Excel 文件 NPOI 是一个用于处理 Microsoft Office 文档的强大 .NET 类库。安装完成后可以在项目中轻松加载并遍历 Excel 表格的内容。 ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; public class ExcelLoader { private IWorkbook workbook; public void LoadExcelFile(string path){ using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); this.workbook = new XSSFWorkbook(fileStream); } public string[,] GetSheetData(int sheetIndex=0){ ISheet sheet = workbook.GetSheetAt(sheetIndex); int rowCount = sheet.LastRowNum + 1; int colCount = sheet.GetRow(0).LastCellNum; string[,] data = new string[rowCount,colCount]; for (int r = 0; r <= rowCount - 1; r++) { IRow row = sheet.GetRow(r); if(row != null){ for (int c = 0; c < colCount; c++){ try{ ICell cell = row.GetCell(c); switch(cell.CellType){ case CellType.String: data[r,c]=cell.ToString(); break; default: data[r,c]=""; break; } }catch(Exception e){ Debug.LogError(e.Message); } } } } return data; } } ``` 这段代码展示了如何创建 `ExcelLoader` 来加载指定路径下的 Excel 文件,并获取特定工作簿内的所有单元格值作为字符串数组返回[^2]。 #### 方法三:采用 ExcelDataReader 插件简化过程 对于只需要读取而不必修改的情况来说,`ExcelDataReader` 提供了一个轻量级的选择。它能够快速有效地导入 Excel 数据到 C# 环境下。 ```csharp using ExcelDataReader; using System.Data; using System.IO; public class SimpleExcelReader { public DataSet ImportFromExcel(string fileName) { using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read)) { using (var reader = ExcelReaderFactory.CreateReader(stream)){ return reader.AsDataSet(new ExcelDataSetConfiguration(){ ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow=true } }); } } } } ``` 上述例子说明了怎样运用 `SimpleExcelReader` 将整个 Excel 工作薄转换成 ADO.NET 的 `DataSet` 对象以便进一步分析和应用。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值