Unity3D读取Excel表格写入Excel表格

系列文章目录

unity工具



👉前言

有时候难免会遇到读取文件写入文件的操作,今天就来记录一下写入读取Excel的操作,阅读可能会花费几分钟时间,不要着急,慢慢赏阅哦,有什么不足,欢迎评论
大家好,我是心疼你的一切,不定时更新Unity开发技巧,觉得有用记得一键三连哦。
下面就让我们进入正文吧 !


提示:以下是本篇文章正文内容,下面案例可供参考

👉一、读取Excel表格

里面读取了表格数据和模型名字进行对比,然后给模型设置新的名字,具体需求还是自己修改代码,读取就是这么读取的,自行测试就好了哦
注意一下,如果代码报错的话,需要导入一下操作Excel的几个dll文件,如果不报错的话,就说明已经导入过了
dll下载链接请自取
代码如下

using Excel;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class ReadExcelController1 : MonoBehaviour
{
    public string excelName;  //表格文件名字
    public Transform cubetrans;
    Dictionary<string, string > tableData = new Dictionary<string, string>();
    // Start is called before the first frame update
    void Start()
    {
        ReadDataGame(ExcelControl(Application.streamingAssetsPath + "/"+excelName+".xlsx"));
        //BianLiModel();
    }
    public void BianLiModel()
    {
        foreach (var item in cubetrans.GetComponentsInChildren <MeshRenderer>())
        {
            if (tableData.ContainsKey(item.name))
            {
                item.name = tableData[item.name];
            }
            else
            {
                Debug.LogError(item.name);
            }
        }
      
    }
    /// <summary>
    /// 表格数据集合
    /// </summary>
    //private DataSet mResultSet;

    /// <summary>
    /// 读取表数据
    /// </summary>
    /// <param name="excelFile">Excel file.</param>
    public DataSet ExcelControl(string excelFile)
    {
        DataSet mResultSet=new DataSet ();
        FileStream mStream = File.Open(excelFile, FileMode.Open, FileAccess.Read);
        IExcelDataReader mExcelReader = ExcelReaderFactory.CreateOpenXmlReader(mStream);
        mResultSet = mExcelReader.AsDataSet();
        return mResultSet;
    }
    public void ReadDataGame(DataSet mResultSet)
    {
        if (mResultSet.Tables.Count < 1)
            return;

        //默认读取第一个数据表
        DataTable mSheet = mResultSet.Tables[0];

        //判断数据表内是否存在数据
        if (mSheet.Rows.Count < 1)
            return;

        //读取数据表行数和列数
        int rowCount = mSheet.Rows.Count;
        int colCount = mSheet.Columns.Count;
        Debug.Log("行:" + rowCount + "列:" + colCount);
        //准备一个列表存储整个表的数据
        List<Dictionary<string, object>> table = new List<Dictionary<string, object>>();

        //读取数据
        for (int i = 1; i < rowCount; i++)
        {
            //准备一个字典存储每一行的数据
            Dictionary<string, object> row = new Dictionary<string, object>();
            string strname="";
            string strname1 = "";
            for (int j = 0; j < 2; j++)
            {
                //读取第1行数据作为表头字段
                string field = mSheet.Rows[0][j].ToString();
         
                //Key-Value对应
                row[field] = mSheet.Rows[i][j];
                //因为我只需要表格前两个数据,所以只保存前两个,有需要全部的把上面的for j<2 改成j<colCount就行了
                if (mSheet.Rows[i][0].ToString()==null)
                {
                    continue;
                }
                //获取表格里面的数据  0就是第一列  1 是第二列
                strname = (mSheet.Rows[i][1].ToString());
                strname1 = (mSheet.Rows[i][0].ToString());

            }
            Debug.Log(strname1 + "  " + strname);
            if (!tableData.ContainsKey (strname1))
            {
                tableData.Add(strname, strname1);
            }
           
            //添加到表数据中
            table.Add(row);
        }
        Debug.Log("添加结束");
    }
    private void Update()
    {

        if (Input.GetKeyDown (KeyCode.K))
        {
            BianLiModel();
        }
    }
}


👉二、写入Excel表格

测试写的把模型子物体名字写入到表格中
具体代码如下

using OfficeOpenXml;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class CreExcelDatas : MonoBehaviour
{
    public string pathExcel;
    public Transform transform1, transform2;
    // Start is called before the first frame update
    void Start()
    {
        pathExcel = Application.streamingAssetsPath + "/数据.xlsx";
        WriteExcel(pathExcel);
    }
    /// <summary>
    /// 写入表格数据
    /// </summary>
    /// <param name="outpath"></param>
    public void WriteExcel(string outpath)
    {
        FileInfo newFile = new FileInfo(outpath);
        //不存在此文件会自动生成文件
        if (newFile.Exists)
        {
            //如果存在就删除数据重新生成
            newFile.Delete();
            newFile = new FileInfo(outpath);
        }    
      
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
            for (int i = 0; i < transform1.childCount; i++)
            {
                //1  就是第一列   2就是第二列    i+1就是第一行  
                worksheet.Cells[i + 1, 1].Value = transform1.GetChild (i).name;
            }
            for (int i = 0; i < transform2.childCount ; i++)
            {
                worksheet.Cells[i + 1, 2].Value = transform2.GetChild(i).name;
            }
         
            package.Save();
            Debug.Log("文件保存完成");
        }
    }

}

接下来在记录一下文件操作和文件夹的操作吧

👉三、Fileinfo和Directoryinfo的操作

对于文件和文件夹的操作,Fileinfo和Directoryinfo是对文件和文件夹进行一些属性类的操作,比如文件的创造,移动,删除,重建,是不能对文件里面具体的内容进行操作的。
FileInfo 类 fileinfo类是对于文件的操作

判断文件存在不存在的方法

 FileInfo strint = new FileInfo(str.ToString());
        if (!strint.Exists )  //如果不存在 就创建
        {
            strint.Create();
        }

下面是directoryinfo类主要是对文件夹进行操作

DirectoryInfo dirinfo = new DirectoryInfo(@"D:\text");
        //获取其父目录;
        if (!dirinfo.Exists)
        //如果该文件夹不存在,则新建一个该文件夹
        {
            dirinfo.Create();
        }
        dirinfo.CreateSubdirectory("这是子目录");

对文件的其他操作,判断存不存在

//1.判断指定路径内是否有指定文件夹-Directory.Exists

  if (System.IO.Directory.Exists()
        {
            Debug.Log("文件夹已经存在");            
        }
        else
        {
        Debug.Log("文件夹不存在");            

        }

//2.判断指定路径内是否有指定文件- File.Exists

if (System.IO.File.Exists()
        {
            Debug.Log("文件已经存在");            
        }
        else
        {
        Debug.Log("文件不存在");            

        }

具体其他的文件操作类,什么写入读取啊请参考我其他文章吧,这里我就不写的了
其他类的链接分享

👉四、壁纸分享

请添加图片描述
请添加图片描述

👉总结

本次总结的就是读取写入表格的操作,有需要会继续添加新的
如能帮助到你,就帮忙点个赞吧,三连更好哦,谢谢
你的点赞就是对博主的支持,有问题记得留言
不定时更新Unity开发技巧,觉得有用记得一键三连哦。么么哒

  • 26
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
Unity读取Excel表格可以使用第三方插件,比如ExcelDataReader和NPOI等。以下是使用ExcelDataReader读取Excel表格的步骤: 1. 在Unity中导入ExcelDataReader插件。可以在Unity Asset Store中搜索ExcelDataReader并下载导入。 2. 准备需要读取Excel表格文件,将其拖拽到Unity项目中的Assets文件夹中。 3. 编写脚本,使用ExcelDataReader读取Excel表格数据。以下是一个简单的示例: ```csharp using UnityEngine; using System.IO; using System.Data; using ExcelDataReader; public class ExcelReader : MonoBehaviour { public string fileName; // Excel文件名 void Start() { // 构造Excel文件路径 string filePath = Path.Combine(Application.dataPath, fileName); // 读取Excel文件 FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read); // 创建ExcelReader对象 IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); // 读取表格数据 DataSet result = excelReader.AsDataSet(); // 输出表格数据 foreach (DataTable table in result.Tables) { foreach (DataRow row in table.Rows) { foreach (DataColumn col in table.Columns) { Debug.Log(row[col]); } } } // 关闭ExcelReader和文件流 excelReader.Close(); stream.Close(); } } ``` 在上述示例中,我们使用ExcelDataReader中的CreateOpenXmlReader方法创建了一个ExcelReader对象,并传入了Excel表格的FileStream。然后,我们使用AsDataSet方法读取表格数据,并通过遍历DataTable、DataRow和DataColumn输出了表格数据。最后,我们需要手动关闭ExcelReader和文件流。 需要注意的是,在使用ExcelDataReader读取Excel表格时,需要根据Excel表格的格式选择不同的读取方法。例如,如果需要读取xls格式的Excel表格,则需要使用CreateBinaryReader方法创建ExcelReader对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心疼你的一切

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值