Unity3D读取Excel表格写入Excel表格

系列文章目录

unity工具


文章目录


👉前言

有时候难免会遇到读取文件写入文件的操作,今天就来记录一下写入读取Excel的操作,阅读可能会花费几分钟时间,不要着急,慢慢赏阅哦,有什么不足,欢迎评论

大家好,我是心疼你的一切,不定时更新Unity开发技巧,觉得有用记得一键三连哦。

下面就让我们进入正文吧 !


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

👉一、读取Excel表格

里面读取了表格数据和模型名字进行对比,然后给模型设置新的名字,具体需求还是自己修改代码,读取就是这么读取的,自行测试就好了哦

注意一下,如果代码报错的话,需要导入一下操作Excel的几个dll文件,如果不报错的话,就说明已经导入过了
dll下载链接请自取

代码如下

csharp 复制代码
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表格

测试写的把模型子物体名字写入到表格中

具体代码如下

csharp 复制代码
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类是对于文件的操作

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

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

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

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

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

csharp 复制代码
//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开发技巧,觉得有用记得一键三连哦。么么哒

相关推荐
Eiceblue2 小时前
使用 C# 将 Excel 转换为 Markdown 表格(含批量转换示例)
开发语言·c#·excel
Java面试题总结3 小时前
使用 Python 设置 Excel 数据验证
开发语言·python·excel
天人合一peng3 小时前
unity 生成标记根据背景色变色为明显的颜色
unity·游戏引擎
魔士于安3 小时前
Unity 超市总动员 超市收银台 超市货架 超市购物手推车 超市常见商品
游戏·unity·游戏引擎·贴图·模型
CandyU23 小时前
Unity —— 数据持久化
unity·游戏引擎
zh路西法3 小时前
【Unity实现Oneshot胶卷显形】游戏窗口化与Win32API的使用
游戏·unity·游戏引擎
迪捷软件4 小时前
显控系统虚拟仿真的工程化路径
游戏引擎·cocos2d
追逐梦想永不停6 小时前
记录一个好用的excel判断数字格式的公式
前端·chrome·excel
Eiceblue6 小时前
C# 如何实现 Word 转 Excel ?分享两种实用方法
c#·word·excel
凡情8 小时前
android隐私合规检测
android·unity