unity中读取和写入Excel表信息

原博客地址:unity3d:windows读写excel,打包exe可用_unity安装excel包-优快云博客文章浏览阅读2.9k次,点赞2次,收藏15次。首先要注意的点: 1.你的unity版本是多少,去对应的安装目录中取dll 2.System.Data.dll 在D:\Program Files\Unity2017.2\Editor\Data\Mono\lib\mono\2.0 3.I18N开头的dll 在 D:\Program Files\Unity2017.2\Editor\Data\Mono\lib\mono\unity 4...._unity安装excel包https://blog.youkuaiyun.com/luoyikun/article/details/81012065

需要加入库文件 Excel.dll 和ICSharpCode.SharpZipLib库文件,官方链接 http://exceldatareader.codeplex.com/

读取Excel

需要添加命名空间    using Excel;

using System.Collections;
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);
        Debug.LogError("stream    " + stream);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);          //读取2007以后版本
        //IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);     //读取2003以后版本

        DataSet result = excelReader.AsDataSet();
        Debug.LogError("result   " + result);
        excelReader.Close();
        

        int columns = result.Tables[0].Columns.Count;
        int rows = result.Tables[0].Rows.Count;

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                string nvalue = result.Tables[0].Rows[i][j].ToString();
                Debug.Log(nvalue);
            }
        }
        return result;
    }

    public static List<DepenceTableData> Load(string path)
    {
        Debug.LogError(path);
        List<DepenceTableData> _data = new List<DepenceTableData>();
        DataSet resultds = ReadExcel(path);
        int column = resultds.Tables[0].Columns.Count;
        int row = resultds.Tables[0].Rows.Count;
        Debug.LogWarning(column + "  " + row);
        for (int i = 1; i < row; i++)
        {
            DepenceTableData temp_data;
            temp_data.instruct = resultds.Tables[0].Rows[i][0].ToString();
            temp_data.word = resultds.Tables[0].Rows[i][1].ToString();
            Debug.Log(temp_data.instruct + "  " + temp_data.word);
            _data.Add(temp_data);
        }
        return _data;
    }

}

public struct DepenceTableData
{
    public string word;
    public string instruct;
}

写入Excel

此时需要一个Excel.dll的姐妹,EPPlus.dll 官方链接 https://epplus.codeplex.com/releases/view/118053

需要添加命名空间    using OfficeOpenXml;

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

public class PrintExcel : MonoBehaviour {
    public List<DepenceTableData> listdata;
    void Start () {
        //读
        Text T = GameObject.Find("Canvas/Text").GetComponent<Text>();
        T.text = "";//清空一开始的文本
        listdata = DoExcel.Load(Application.streamingAssetsPath + "/Test2003.xls");
        Debug.LogError("listdata"+listdata);
       
        foreach (var listing in listdata)
        {

            Debug.LogError("listing.instruct" + listing.instruct);

            Debug.LogError("listing.word" + listing.word);

            //print(listing.instruct + "     " + listing.word);
            
            T.text += (listing.instruct + "     " + listing.word + "\n").ToString();
        }

        //写
        WriteExcel(Application.streamingAssetsPath + "/Test2007.xlsx");

    }


    public static void WriteExcel(string outputDir)
    {
        //string outputDir = EditorUtility.SaveFilePanel("Save Excel", "", "New Resource", "xlsx");
        FileInfo newFile = new FileInfo(outputDir);
        if (newFile.Exists)
        {
            newFile.Delete();  // ensures we create a new workbook
            newFile = new FileInfo(outputDir);
        }
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            // add a new worksheet to the empty workbook
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
            //Add the headers
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Product";
            worksheet.Cells[1, 3].Value = "Quantity";
            worksheet.Cells[1, 4].Value = "Price";
            worksheet.Cells[1, 5].Value = "Value";

            //Add some items...
            worksheet.Cells["A2"].Value = 12001;
            worksheet.Cells["B2"].Value = "Nails";
            worksheet.Cells["C2"].Value = 37;
            worksheet.Cells["D2"].Value = 3.99;

            worksheet.Cells["A3"].Value = 12002;
            worksheet.Cells["B3"].Value = "Hammer";
            worksheet.Cells["C3"].Value = 5;
            worksheet.Cells["D3"].Value = 12.10;

            worksheet.Cells["A4"].Value = 12003;
            worksheet.Cells["B4"].Value = "Saw";
            worksheet.Cells["C4"].Value = 12;
            worksheet.Cells["D4"].Value = 15.37;

            //save our new workbook and we are done!
            package.Save();
        }
    }


}

网上下载对应(Excel.dll 和ICSharpCode.SharpZipLib)Dll文件

优快云资源地址:https://download.youkuaiyun.com/download/u3dcoder/10690538?spm=1001.2014.3001.5503

Unity项目中,Excel通常用于存储游戏数据、配置信息等,并通过脚本实现对Excel文件的读取写入操作。以下是关于如何在Unity中处理Excel文件的基本流程: ### Excel 读取 1. **将Excel转换为CSV** Unity本身无法直接解析.xlsx格式的Excel文档,因此需要先将其保存为.csv(逗号分隔值)格式。 2. **加载CSV文件内容到内存** 使用C#提供的`StreamReader`可以逐行读取CSV文本内容,并分割每列的数据以便进一步使用。 ```csharp using System.Collections; using System.IO; public class CSVReader { public static List<string[]> Read(string filePath) { var result = new List<string[]>(); using (var reader = new StreamReader(filePath)) { while (!reader.EndOfStream){ string line = reader.ReadLine(); if(!string.IsNullOrEmpty(line)){ result.Add(line.Split(',')); } } } return result; // 返回每一行作为字符串数组组成的列 } } ``` 3. **映射到数据结构** 将从CSV得到的数据存放到自定义对象集合里方便后续引用。 --- ### 写入Excel(实际一般导出成CSV) 由于标准库缺乏对Excel(.xlsx/.xls)的支持,如果只是简单地生成格建议依然采用CSV形式;如果是复杂需求,则需引入第三方插件如EPPlus或NPOI。 示例 - 创建新的CSV并添加记录: ```csharp System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.AppendLine("Name,Age,Score"); foreach(var player in players){ builder.Append(player.Name+","); builder.Append(player.Age+","); builder.Append(player.Score); } File.WriteAllText(Application.dataPath + "/output.csv", builder.ToString()); ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值