Unity 读取Excel工作表 以及排行榜的制作

一、读取Excel

/// 
    ///返回数据的集合 
    ///数据的格式为 每一行为一条数据
    ///例:"Me|40|29|2019530" 
    /// 
    /// 
    public List LoadData()
    {
        // StreamingAssets目录下的  党员信息.xlsx文件的路径:Application.streamingAssetsPath + "/党员信息.xlsx" 
        FileStream fileStream = File.Open(Application.streamingAssetsPath + "/排行榜.xlsx",     
        FileMode.Open, FileAccess.Read);
        IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
        // 表格数据全部读取到result里
        DataSet result = excelDataReader.AsDataSet();

        // 获取表格有多少列 
        int columns = result.Tables[0].Columns.Count;
        // 获取表格有多少行 
        int rows = result.Tables[0].Rows.Count;

        //获取表格的行数 -1去掉第一行
        //testRow = rows - 1;

        //Debug.Log("行" + rows);
        // 根据行列依次打印表格中的每个数据 

        List excelDta = new List();

        //第一行为表头,不读取
        for (int i = 1; i < rows; i++)
        {
            value = null;
            all = null;
            for (int j = 0; j < columns; j++)
            {
                // 获取表格中指定行指定列的数据 
                value = result.Tables[0].Rows[i][j].ToString();
                //Debug.Log("value = " + value);
                if (value == "")
                {
                    continue;
                }
                all = all + value + "|";
            }
            if (all != null)
            {
                print(all);
                excelDta.Add(all);
            }
        }
        return excelDta;
    }

二、重新写入Excel

 /// 
    /// list内容格式
    /// "Me|40|29|2019530" 
    /// 
    /// 
    public void WriteExcel(List newList)
    {
        //自定义excel的路径

        string path = Application.streamingAssetsPath + "/排行榜.xlsx";
        // print(Application.dataPath);

        FileInfo newFile = new FileInfo(path);

        if (newFile.Exists)
        {
            //创建一个新的excel文件

            newFile.Delete();

            newFile = new FileInfo(path);
        }

        //通过ExcelPackage打开文件
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            //在excel空文件添加新sheet

            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("message");
            //添加列名

            worksheet.Cells[1, 1].Value = "playerName";

            worksheet.Cells[1, 2].Value = "accuracy";

            worksheet.Cells[1, 3].Value = "usedTime";

            worksheet.Cells[1, 4].Value = "rankingTime";

            for (int i = 0; i < newList.Count; i++)
            {
                string[] messages = newList[i].Split('|'); //赵一|党员|1年|赵一.png| 
                string itemName = messages[0];
                string itemWork = messages[1];
                string itemYear = messages[2];
                string imageName = messages[3];
                //添加一行数据

                int num = i + 2;

                worksheet.Cells["A" + num].Value = itemName;

                worksheet.Cells["B" + num].Value = itemWork;

                worksheet.Cells["C" + num].Value = itemYear;

                worksheet.Cells["D" + num].Value = imageName;
            }

            //保存excel
            package.Save();
            print("重写完成");
        }
    }

三、排行榜的制作

 /// 
    /// tmpSubmit - 游戏结束输入
    /// 
    public void SubmitRanking(string tmpSubmit)
    {
        startRanking = LoadData();

        Debug.Log(startRanking.Count);
        //Debug.Log("Excel:"+startRanking.Count);
        //Debug.Log("EndExcel:"+startRanking[startRanking.Count-1]);
        if (startRanking.Count == 8)
        {
            if (FloatReckonRatio(startRanking[startRanking.Count - 1]) < FloatReckonRatio(tmpSubmit))
            {
                startRanking[startRanking.Count - 1] = tmpSubmit;
                ListSort(startRanking);
                //Debug.Log(startRanking[startRanking.Count-1]);
                //把最后一面顶替掉然后进行排序
                Debug.Log("进入排行榜成功");
            }
            else
            {
                Debug.Log("进入排行榜失败");
            }

            Debug.Log("有八位数据");
        }
        else
        {
            startRanking.Add(tmpSubmit);
            ListSort(startRanking);
            Debug.Log("未够十位数");
        }

        startRanking = LoadData();
        for (int i = 0; i < startRanking.Count; i++)
        {
            Debug.Log(startRanking[i]);
        }
    }

    /// 
    /// 计算是 占比值 玩家分数
    /// 
    /// 
    /// 
    public float FloatReckonRatio(string tmpFormerRan)
    {
        float ratioFloat = 0;

        for (int i = 0; i < tmpFormerRan.Length; i++)
        {
            string[] tmpString = tmpFormerRan.Split('|');

            float accuracy = float.Parse(tmpString[1]) / 100f;
            float usedTime = 1 / float.Parse(tmpString[2]);
            float total = accuracy + usedTime;

            ratioFloat = total;
        }
        return ratioFloat;
    }

    /// 
    /// 让List进行重新排序排序
    /// 
    /// 
    public List ListSort(List tmpList)
    {
        List _tmpData = new List();

        //数据至少有两个 才开始进行排序
        if (tmpList.Count > 1)
        {
            _tmpData = tmpList;
            for (int i = 0; i < _tmpData.Count; i++)
            {
                for (int j = 0; j < _tmpData.Count - 1 - i; j++)
                {
                    if (FloatReckonRatio(_tmpData[j]) < FloatReckonRatio(_tmpData[j + 1]))
                    {
                        string data = _tmpData[j];
                        _tmpData[j] = _tmpData[j + 1];
                        _tmpData[j + 1] = data;
                    }
                }
            }
        }
        else
        {
            _tmpData = tmpList;
        }

        //读取重新建表
        WriteExcel(_tmpData);
        return _tmpData;
    }

整个脚本

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

public class TestExcel : MonoBehaviour
{

    public static TestExcel instance;
    string value;
    string all;
    int testRow;

    private List storageExcel = new List();
    private List startRanking;              //开始的时候存储的排行榜数据
    private string submit;

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        submit = "Me|40|29|2019530";
        SubmitRanking(submit);
    }

    /// 
    ///返回数据的集合 
    ///数据的格式为 每一行为一条数据
    ///例:"Me|40|29|2019530" 
    /// 
    /// 
    public List LoadData()
    {
        // StreamingAssets目录下的  党员信息.xlsx文件的路径:Application.streamingAssetsPath + "/党员信息.xlsx" 
        FileStream fileStream = File.Open(Application.streamingAssetsPath + "/排行榜.xlsx", FileMode.Open, FileAccess.Read);
        IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
        // 表格数据全部读取到result里
        DataSet result = excelDataReader.AsDataSet();

        // 获取表格有多少列 
        int columns = result.Tables[0].Columns.Count;
        // 获取表格有多少行 
        int rows = result.Tables[0].Rows.Count;

        //获取表格的行数 -1去掉第一行
        //testRow = rows - 1;

        //Debug.Log("行" + rows);
        // 根据行列依次打印表格中的每个数据 

        List excelDta = new List();

        //第一行为表头,不读取
        for (int i = 1; i < rows; i++)
        {
            value = null;
            all = null;
            for (int j = 0; j < columns; j++)
            {
                // 获取表格中指定行指定列的数据 
                value = result.Tables[0].Rows[i][j].ToString();
                //Debug.Log("value = " + value);
                if (value == "")
                {
                    continue;
                }
                all = all + value + "|";
            }
            if (all != null)
            {
                print(all);
                excelDta.Add(all);
            }
        }
        return excelDta;
    }

    /// 
    /// list内容格式
    /// "Me|40|29|2019530" 
    /// 
    /// 
    public void WriteExcel(List newList)
    {
        //自定义excel的路径

        string path = Application.streamingAssetsPath + "/排行榜.xlsx";
        // print(Application.dataPath);

        FileInfo newFile = new FileInfo(path);

        if (newFile.Exists)
        {
            //创建一个新的excel文件

            newFile.Delete();

            newFile = new FileInfo(path);
        }

        //通过ExcelPackage打开文件
        using (ExcelPackage package = new ExcelPackage(newFile))
        {
            //在excel空文件添加新sheet

            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("message");
            //添加列名

            worksheet.Cells[1, 1].Value = "playerName";

            worksheet.Cells[1, 2].Value = "accuracy";

            worksheet.Cells[1, 3].Value = "usedTime";

            worksheet.Cells[1, 4].Value = "rankingTime";

            for (int i = 0; i < newList.Count; i++)
            {
                string[] messages = newList[i].Split('|'); //赵一|党员|1年|赵一.png| 
                string itemName = messages[0];
                string itemWork = messages[1];
                string itemYear = messages[2];
                string imageName = messages[3];
                //添加一行数据

                int num = i + 2;

                worksheet.Cells["A" + num].Value = itemName;

                worksheet.Cells["B" + num].Value = itemWork;

                worksheet.Cells["C" + num].Value = itemYear;

                worksheet.Cells["D" + num].Value = imageName;
            }

            //保存excel
            package.Save();
            print("重写完成");
        }
    }

    /// 
    /// tmpSubmit - 游戏结束输入
    /// 
    public void SubmitRanking(string tmpSubmit)
    {
        startRanking = LoadData();

        Debug.Log(startRanking.Count);
        //Debug.Log("Excel:"+startRanking.Count);
        //Debug.Log("EndExcel:"+startRanking[startRanking.Count-1]);
        if (startRanking.Count == 8)
        {
            if (FloatReckonRatio(startRanking[startRanking.Count - 1]) < FloatReckonRatio(tmpSubmit))
            {
                startRanking[startRanking.Count - 1] = tmpSubmit;
                ListSort(startRanking);
                //Debug.Log(startRanking[startRanking.Count-1]);
                //把最后一面顶替掉然后进行排序
                Debug.Log("进入排行榜成功");
            }
            else
            {
                Debug.Log("进入排行榜失败");
            }

            Debug.Log("有八位数据");
        }
        else
        {
            startRanking.Add(tmpSubmit);
            ListSort(startRanking);
            Debug.Log("未够十位数");
        }

        startRanking = LoadData();
        for (int i = 0; i < startRanking.Count; i++)
        {
            Debug.Log(startRanking[i]);
        }
    }

    /// 
    /// 计算是 占比值 玩家分数
    /// 
    /// 
    /// 
    public float FloatReckonRatio(string tmpFormerRan)
    {
        float ratioFloat = 0;

        for (int i = 0; i < tmpFormerRan.Length; i++)
        {
            string[] tmpString = tmpFormerRan.Split('|');

            float accuracy = float.Parse(tmpString[1]) / 100f;
            float usedTime = 1 / float.Parse(tmpString[2]);
            float total = accuracy + usedTime;

            ratioFloat = total;
        }
        return ratioFloat;
    }

    /// 
    /// 让List进行重新排序排序
    /// 
    /// 
    public List ListSort(List tmpList)
    {
        List _tmpData = new List();

        //数据至少有两个 才开始进行排序
        if (tmpList.Count > 1)
        {
            _tmpData = tmpList;
            for (int i = 0; i < _tmpData.Count; i++)
            {
                for (int j = 0; j < _tmpData.Count - 1 - i; j++)
                {
                    if (FloatReckonRatio(_tmpData[j]) < FloatReckonRatio(_tmpData[j + 1]))
                    {
                        string data = _tmpData[j];
                        _tmpData[j] = _tmpData[j + 1];
                        _tmpData[j + 1] = data;
                    }
                }
            }
        }
        else
        {
            _tmpData = tmpList;
        }

        //读取重新建表
        WriteExcel(_tmpData);
        return _tmpData;
    }
}

读取Excel的百度网盘路径D文件:
链接:https://pan.baidu.com/s/1VrBqEdUDsiP_Z3pGi0CqOg
提取码:t2lt

为避免打包exe后读取不到excel数据,须将
Unity\Editor\Data\Mono\lib\mono\unity目录下的一系列i18n相关dll导入项目Plugins文件夹中。

你可能感兴趣的:(Unity 读取Excel工作表 以及排行榜的制作)