Unity数据持久化 之 一个通过2进制读取Excel并存储的轮子(1)

本文仅作笔记学习和分享,不用做任何商业用途

本文包括但不限于unity官方手册,unity唐老狮等教程知识,如有不足还请斧正​​

 事先声明:该工具我是跟唐老师教程来的,并非原创,仅作学习笔记交流

1.需求分析

最终目的就如标题,到时什么表都可以拿来直接读岂不美哉

2.指定配表规则

唐老狮的表我就直接拿来用了

 

有两张表以作示范 

 

 3.读取Excel下的所有工作表

PS:这就不得提到文件夹操作相关的api了

Windows.Directory - Unity 脚本 API

使用这个api,如果已经有该目录,则返回该目录

 废话不多说,上代码

using Excel;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ExcelTools : MonoBehaviour
{
    // 表格文件夹的路径
    private static string Excel_Path = Application.dataPath + "/Excel";

    // 生成和读取表格的方法
    [MenuItem("Tool/GenerateExcel")]
    private static void GenerateExcelInfo()
    {
        // 创建或返回表格文件夹的路径
        DirectoryInfo directoryInfo = Directory.CreateDirectory(Excel_Path);
        // 获取文件夹中的所有文件
        FileInfo[] fileInfo = directoryInfo.GetFiles();
        // 数据表集合
        DataTableCollection dataTableCollection;

        for (int i = 0; i < fileInfo.Length; i++)
        {
            // 筛选出扩展名为 .xlsx 或 .xls 的文件
            if (fileInfo[i].Extension != ".xlsx" && fileInfo[i].Extension != ".xls")
                continue;

            // 打开文件流读取表格
            using (FileStream fs = fileInfo[i].Open(FileMode.Open, FileAccess.Read))
            {
                // 使用 IExcelDataReader 读取表格数据
                IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
                dataTableCollection = excelDataReader.AsDataSet().Tables; // 转换为数据表集合
                fs.Close();
            }

            // 输出每个工作表的名称
            foreach (DataTable temp in dataTableCollection)
            {
                Debug.Log(temp.TableName);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值