当前位置:网站首页>关于unity文件读取的操作(一)

关于unity文件读取的操作(一)

2022-04-23 18:32:00 孟尘双喜

记录一下unity如何进行文件读取的操作

1.关于Excel文件的读取和写入:

这里的线索来源于买的一本书,书名《unity3D游戏开发(第二版)》,作者是宣雨松他这里面提到的使用一个DLL插件可以很方便的进行文件的读写创建等操作。Epplus这个可以在B站或者是VS的包管理也可以直接导入,或者需要的也可以找我。代码如下:

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

public class PrintExcel : MonoBehaviour
{
void Start()
{
LoadExcel();
AddExcel();
}

public static void LoadExcel()
{
    string path = Application.dataPath + "/Excel/test.xlsx";
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (ExcelPackage excel=new ExcelPackage(fs))
        {
            ExcelWorksheets excelWorksheets = excel.Workbook.Worksheets;//获得所有表格
            Debug.Log("表数:"+excelWorksheets.Count);
            for (int i = 1; i <= excelWorksheets.Count; i++)//从下标1开始
            {                    
                ExcelWorksheet worksheet = excelWorksheets[i];
                int colCount = worksheet.Dimension.End.Column;
                Debug.Log(worksheet.Name);

                for(int row = 1, count = worksheet.Dimension.End.Row; row <= count; row++)
                {
                    for(int col = 1; col <= colCount; col++)
                    {
                        //读取每个单元格的内容
                        var text = worksheet.Cells[row, col].Text;
                        Debug.Log(text);
                    }
                }
            }
        }
    }
}

public static void AddExcel()
{
    string path = Application.dataPath + "/Excel/test.xlsx";
    var file = new FileInfo(path);
    using (ExcelPackage excel=new ExcelPackage(file))
    {
        ExcelWorksheet worksheet2 = excel.Workbook.Worksheets.Add("Sheet3");//(如果已存在会报错,所以这里需要判断)
        worksheet2.Cells[1, 1].Value = "公司名";
        worksheet2.Cells[1, 2].Value = "地址";
        excel.Save();
    }
    AssetDatabase.Refresh();
}
}

需要注意的是 string path = Application.dataPath + “/Excel/test.xlsx”,路径一定要写对,我这个代码写的是全部读取并展示。 还有一点 for (int i = 1; i <= excelWorksheets.Count; i++),表格实际上是从从下标1开始的

2.关于word文档的读取

这个比较久远了,也是查别人的代码找到的,链接没法给了。代码如下:

			DirectoryInfo d = new DirectoryInfo(LoadVariables.rootPATH + "/"+LoadVariables.loadScene);//路径
            DirectoryInfo[] dc = d.GetDirectories();//获得文件夹
            
                FileInfo[] files = d.GetFiles("*.txt");//获得txt文件
                Debug.Log(files.Length);                 
                for (int i = 0; i < files.Length; i++)
                {
                    string a=File.ReadAllText(LoadVariables.rootPATH + "/"+LoadVariables.loadScene+"/"+files[i].Name);//读取文件             
                }

版权声明
本文为[孟尘双喜]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_37900417/article/details/124294692