Excel 读写

![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/0a5b4228fa22468da0c706727a4fba96.png
在这里插入图片描述

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

public class ExcelMgrHelp : Singleton<ExcelMgrHelp>
{

    public void Start()
    {
        string _filePath = Application.streamingAssetsPath + "/学生信息.xlsx";
        WriteExcel(_filePath);
        ReadExcel(_filePath);


        _filePath = Application.streamingAssetsPath + "/DataTest.xlsx";
        List<DataTest> datas = new List<DataTest> {
           new DataTest(0,"先民",100,1.85f) ,
           new DataTest(1,"星宇",110,1.5f) ,
           new DataTest(2,"刘敏",10,1.8f)
        };

        WriteExcel(_filePath, datas);
        List<DataTest> datas2 = ReadExcel<DataTest>(_filePath);

    }

    void WriteExcel(string _filePath)
    {
        string _sheetName = "详情";
        FileInfo fileInfo = new FileInfo(_filePath);
        if (fileInfo.Exists)
        {
            fileInfo.Delete();   //删除旧文件,并创建一个新的 excel 文件。
            fileInfo = new FileInfo(_filePath);
        }

        //通过ExcelPackage打开文件
        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            //在 excel 空文件添加新 sheet,并设置名称。
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(_sheetName);

            //添加列名
            worksheet.Cells[1, 1].Value = "学号";
            worksheet.Cells[1, 2].Value = "姓名";
            worksheet.Cells[1, 3].Value = "性别";

            //添加一行数据
            worksheet.Cells[2, 1].Value = 100001;
            worksheet.Cells[2, 2].Value = "张三";
            worksheet.Cells[2, 3].Value = "男";

            //添加一行数据
            worksheet.Cells[3, 1].Value = 100002;
            worksheet.Cells[3, 2].Value = "李四";
            worksheet.Cells[3, 3].Value = "女";

            //添加一行数据
            worksheet.Cells[4, 1].Value = 120033;
            worksheet.Cells[4, 2].Value = "Saw";
            worksheet.Cells[4, 3].Value = "男";

            //保存excel
            package.Save();
        }
    }

    void ReadExcel(string _filePath)
    {
        //获取Excel文件的信息
        FileInfo fileInfo = new FileInfo(_filePath);
        if (!fileInfo.Exists)
            return;

        using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
        {
            ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[1];
            int rowCount = worksheet.Dimension.End.Row;
            int columnCount = worksheet.Dimension.End.Column;
            for (int i = 0; i < rowCount; i++)//End.Row获得当前表格的最大行数
            {
                string str = null;
                for (int j = 0; j < columnCount; j++)
                {
                    str += worksheet.Cells[i + 1, j + 1].Value.ToString();
                    if (j < columnCount - 1)
                    {
                        str += ",";
                    }
                }
                Debug.Log($"ReadExcel: line {i + 1} " + str);
            }
        }
    }


   

    public void WriteExcel<T>(string _filePath, List<T> datas) where T : BaseData
    {
        if (datas == null || datas.Count <= 0 || string.IsNullOrEmpty(_filePath))
            return;

        FileInfo fileInfo = new FileInfo(_filePath);
        if (fileInfo.Exists)
        {
            fileInfo.Delete();   //删除旧文件,并创建一个新的 excel 文件。
            fileInfo = new FileInfo(_filePath);
        }

        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            WriteExcel(package, datas);
        }
    }

    public void WriteExcel<T>(ExcelPackage package, List<T> datas) where T : BaseData
    {
        BaseData data = datas[0];
        string _sheetName = data.GetType().Name;

        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(_sheetName); //在 excel 空文件添加新 sheet,并设置名称。


        //变量名、变量类型、 注释
        string[,] keys = data.GetDataKey();
        int rowKey = 3;
        int columnKey = keys.Length / rowKey;

        //rowKey = 0;

        for (int i = 0; i < rowKey; i++)
        {
            for (int j = 0; j < columnKey; j++)
            {
                worksheet.Cells[i + 1, j + 1].Value = keys[i, j];
            }
        }

        //数据
        int row = datas.Count;
        for (int i = 0; i < row; i++)
        {
            data = datas[i];
            string[] valueArr = data.GetDataValue();
            int column = valueArr.Length;
            for (int j = 0; j < column; j++)
            {
                worksheet.Cells[i + 1 + rowKey, j + 1].Value = valueArr[j];
            }
        }

        //保存excel
        package.Save();
    }



    public List<T> ReadExcel<T>(string _filePath) where T : BaseData
    {
        if (string.IsNullOrEmpty(_filePath))
            return null;


        FileInfo fileInfo = new FileInfo(_filePath);
        if (!fileInfo.Exists)
            return null;

        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            List<T> datas = ReadExcel<T>(package); 

            return datas;
        }  
    }

    public List<T> ReadExcel<T>(byte[] bytes) where T : BaseData
    {
        if (bytes == null || bytes.Length <= 0)
            return null;

        Stream fileInfo = new MemoryStream(bytes);

        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            List<T> datas = ReadExcel<T>(package);

            return datas;
        } 
    }

    public List<T> ReadExcel<T>(ExcelPackage package) where T : BaseData
    {

        List<T> datas = new List<T>();

        //通过ExcelPackage打开文件

        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int rowCount = worksheet.Dimension.End.Row;
        int columnCount = worksheet.Dimension.End.Column;

        int rowKey = 3;
        //变量名、变量类型、 注释
        string[,] keys = new string[rowKey, columnCount];
        for (int i = 0; i < rowKey; i++)
        {
            for (int j = 0; j < columnCount; j++)
            {
                keys[i, j] = worksheet.Cells[i + 1, j + 1].Value?.ToString();
            }
        }

        //数据
        for (int i = rowKey; i < rowCount; i++)
        {
            object obj = Activator.CreateInstance(typeof(T));
            T t = (T)obj;
            //方式1
            for (int j = 0; j < columnCount; j++)
            {
                string FieldName = keys[0, j];
                string FieldType = keys[1, j];
                string Value = worksheet.Cells[i + 1, j + 1].Value?.ToString();

                Type Ts = obj.GetType();
                System.Reflection.FieldInfo info = Ts.GetField(FieldName);
                if (!string.IsNullOrEmpty(Value))
                    info.SetValue(obj, Value.GetTypeStr(FieldType));
            }

            //方式2
            //t.SetDataValue(worksheet.Cells, i + 1, 1);

            Debug.Log(t.ToString());
            datas.Add(t);
        }

        return datas;
    }


}


public static class Utils
{
    public static string GetTypeStr(this System.Type type)
    {

        if (type == typeof(string))
        {
            return "string";
        }
        else if (type == typeof(float))
        {
            return "float";
        }
        else if (type == typeof(int))
        {
            return "int";
        }
        else if (type == typeof(long))
        {
            return "long";
        }
        else if (type == typeof(double))
        {
            return "double";
        }
        else if (type == typeof(byte))
        {
            return "byte";
        }
        else if (type == typeof(DateTime))
        {
            return "DateTime";
        }

        return type.Name;
    }

    public static object GetTypeStr(this string Value, string FieldType)
    {
        switch (FieldType)
        {
            case "string": return Value;
            case "float": return float.Parse(Value);
            case "int": return int.Parse(Value);
            case "long": return long.Parse(Value);
            case "double": return double.Parse(Value);
            case "byte": return byte.Parse(Value);
            case "DateTime": return System.DateTime.Parse(Value);

            default: break;
        }

        return Value;
    }
}

public interface BaseData
{
    public abstract string[] GetDataValue();

    public abstract string[,] GetDataKey();

    public abstract void SetDataValue(ExcelRange cell, int row, int cloumn);

    public abstract string ToString();
}

class DataTest : BaseData
{
    public int id;
    public string name;
    public int leve;
    public float height;

    public DataTest()
    {

    }

    public DataTest(int _id, string _name, int _leve, float _height)
    {
        id = _id;
        name = _name;
        leve = _leve;
        height = _height;
    }


    public virtual string[,] GetDataKey()
    {
        return new string[,] {
        { nameof(id)  ,  nameof(name) , nameof(leve),  nameof(height) },
        { id.GetType().GetTypeStr(), name.GetType().GetTypeStr(), leve.GetType().GetTypeStr(), height.GetType().GetTypeStr()},
        { "唯一ID", "姓名", "等级", "身高" }
        };
    }

    public virtual string[] GetDataValue()
    {
        return new string[] { id.ToString(), name.ToString(), leve.ToString(), height.ToString() };
    }

    public virtual void SetDataValue(ExcelRange cell, int row, int cloumn)
    {
        id = int.Parse(cell[row, cloumn].Value.ToString());
        name = cell[row, cloumn + 1].Value.ToString();
        leve = int.Parse(cell[row, cloumn + 2].Value.ToString());
        height = float.Parse(cell[row, cloumn + 3].Value.ToString());
    }

    public override string ToString()
    {
        return string.Format("{0}: {1} {2} {3} {4}", typeof(DataTest), id, name, leve, height);
    }

}

编辑器 csv 、Excel 生成 脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEditor;
using System.Text;
using System.IO;
using OfficeOpenXml;
using System;

public class ExcelcsvEditor
{
    [MenuItem("Assets/cwl/csv to cs")]
    static void ReadData_csv()
    {
        string userFile_Path = AssetDatabase.GetAssetPath(Selection.activeObject);
        //string userFile_Path = Application.streamingAssetsPath + "/csv/";

        int endindex = userFile_Path.LastIndexOf('.');
        if (endindex == -1)
        {
            string[] files = Directory.GetFiles(userFile_Path, "*.csv", SearchOption.AllDirectories);
            for (int i = 0; i < files.Length; i++)
            {
                ReadData_csv(files[i].Replace("\\", "/"));
            }
        }
        else
        {
            ReadData_csv(userFile_Path);
        }
    }

    static void ReadData_csv(string userFile_Path)
    {
        //string userFile_Path = Application.streamingAssetsPath + string.Format("/Configs/{0}.csv", fileName);

        string getString = File.ReadAllText(userFile_Path);
        CsvReaderByString csr = new CsvReaderByString(getString);

        // 读取数据
        int row = csr.RowCount;
        int cloumn = csr.ColCount;
        Debug.Log(row + " , " + cloumn);

        int endindex = userFile_Path.LastIndexOf('.');
        int stindex = userFile_Path.LastIndexOf('/');
        stindex++;
        string fileName = userFile_Path.Substring(stindex, endindex - stindex);

        string CreateClassAction(int row, int cloum)
        {
            return csr[row, cloum];
        }

        string data = CreateClass(CreateClassAction, row, cloumn, fileName);
        string fname = Path.GetDirectoryName(userFile_Path);
        string className = fileName + ".cs";

        IOUtil.CreateFile(fname + $"/{className}", data);
        //IOUtil.CreateFile(Application.dataPath+ @"\Scripts\Common\Game\Define\GameConfigs\GameConfigs_SQL" + $"/{className}", data); 
        AssetDatabase.Refresh();


    }


    [MenuItem("Assets/cwl/excel to cs")]
    static void ReadData_Excel()
    {
        //string userFile_Path = Environment.CurrentDirectory + "/AppRes/Excels/Register/新用户信息 - 副本.xlsx";
        //string userFile_Path = Application.streamingAssetsPath + "/DataTest.xlsx";
        string userFile_Path = AssetDatabase.GetAssetPath(Selection.activeObject);

        int endindex = userFile_Path.LastIndexOf('.');
        if (endindex == -1)
        {
            string[] files = Directory.GetFiles(userFile_Path, "*.xlsx", SearchOption.AllDirectories);
            for (int i = 0; i < files.Length; i++)
            {
                ReadData_Excel(files[i].Replace("\\", "/"));
            }
        }
        else
        {
            ReadData_Excel(userFile_Path);
        }
    }

    static void ReadData_Excel(string userFile_Path)
    {
        FileInfo fileInfo = new FileInfo(userFile_Path);
        using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
        {
            ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[1];

            // 读取数据
            int row = worksheet.Dimension.End.Row;
            int cloumn = worksheet.Dimension.End.Column;
            string fileName = worksheet.Name;
            Debug.Log(row + " , " + cloumn);

            string CreateClassAction(int row, int cloum)
            {
                return worksheet.Cells[row, cloum].Value.ToString();
            }

            string data = CreateClass(CreateClassAction, row, cloumn, fileName);
            string fname = Path.GetDirectoryName(fileInfo.FullName);
            string className = fileInfo.Name.Replace(fileInfo.Extension, ".cs");

            IOUtil.CreateFile(fname + $"/{className}", data);
            //IOUtil.CreateFile(Application.dataPath + @"\Scripts\Common\Game\Define\GameConfigs\GameConfigs_SQL" + $"/{className}", data);
        }

        AssetDatabase.Refresh();
    }

    static string CreateClass(Func<int, int, string> GetCell, int row, int cloumn, string className)
    {
        //1 id
        //2 int
        //3 注释
        //4-》 数据
        //string className = null;
        string dataKey1 = null, dataKey2 = null, dataKey3 = null;
        string getdataValue = null, setdataValue = null, tostring = null;
        string ctorParameter = null, ctorValue = null;

        //className = worksheet.Name;
        StringBuilder bulider = new StringBuilder();

        bulider.AppendLine("using System.Collections.Generic;");
        bulider.AppendLine("using System;");
        bulider.AppendLine("using OfficeOpenXml;");
        bulider.AppendLine();
        bulider.AppendLine("//代码生成,勿动");
        bulider.AppendLine();
        bulider.AppendLine(string.Format("public partial class {0}: GameConfigDataBase,BaseData", className));
        bulider.AppendLine("{");
        for (int j = 0; j < cloumn; j++)
        {
            int curCloumn = j + 1;

            string typeName = GetCell(1, curCloumn);  //1 id
            string mtype = GetCell(2, curCloumn); //2 int
            string zushi = GetCell(3, curCloumn); //3 注释

            //属性  
            bulider.AppendLine("   /// <summary>");
            bulider.AppendLine(string.Format("   /// {0}", zushi));
            bulider.AppendLine("   /// <summary>");
            bulider.AppendLine(string.Format("   public {0} {1};", mtype, typeName));
            bulider.AppendLine("");

            //构造函数 无参

            //构造函数 有参
            ctorParameter += ($"{mtype} _{typeName}");
            ctorValue += ($"        {typeName} = _{typeName};\r\n");

            //GetDataKey
            dataKey1 += $"nameof({typeName})";
            dataKey2 += $"\"{mtype}\"";//$"{typeName}.GetType().GetTypeStr()";
            dataKey3 += $"\"{zushi}\"";

            //GetDataValue
            getdataValue += $"{typeName } == null ? null : {typeName }.ToString()";

            //GetDataValue  
            if (setdataValue == null)
                setdataValue += $"        object obj = null;\r\n";

            setdataValue += $"        obj = cell[row, cloumn + {j}].Value;\r\n";
            setdataValue += $"        {typeName} =";
            if (mtype == "string")
            {
                setdataValue += $"obj == null ?default: obj.ToString();";
            }
            else
            {
                setdataValue += $"obj == null ? default : {mtype}.Parse(obj.ToString());";
            }
            setdataValue += "\r\n";

            //ToString()
            tostring += $"{{{typeName}}}";

            if (j < cloumn - 1)
            {
                dataKey1 += ",";
                dataKey2 += ",";
                dataKey3 += ",";
                getdataValue += ",";
                tostring += " ";

                ctorParameter += ", ";
            }
        }

        bulider.AppendLine();
        bulider.AppendLine("    public override string getFilePath()");
        bulider.AppendLine("	{");
        bulider.AppendLine($"		return \"{className}\";");
        bulider.AppendLine("	}");
        bulider.AppendLine();

        bulider.AppendLine();
        bulider.AppendLine($"    public {className}()");
        bulider.AppendLine("	{");
        bulider.AppendLine();
        bulider.AppendLine("	}");
        bulider.AppendLine();

        bulider.AppendLine();
        bulider.AppendLine($"    public {className}({ctorParameter})");
        bulider.AppendLine("	{");
        bulider.AppendLine($"{ctorValue}");
        bulider.AppendLine("	}");
        bulider.AppendLine();

        bulider.AppendLine();
        bulider.AppendLine("    public virtual string[,] GetDataKey()");
        bulider.AppendLine("	{");
        bulider.AppendLine("        return new string[,] {");
        bulider.AppendLine($"        {{{dataKey1}}},");
        bulider.AppendLine($"        {{{dataKey2}}},");
        bulider.AppendLine($"        {{{dataKey3}}}");
        bulider.AppendLine("        };");
        bulider.AppendLine("	}");
        bulider.AppendLine();

        bulider.AppendLine();
        bulider.AppendLine("    public virtual string[] GetDataValue()");
        bulider.AppendLine("	{");
        bulider.AppendLine($"        return new string[] {{{getdataValue}}};");
        bulider.AppendLine("	}");
        bulider.AppendLine();

        bulider.AppendLine();
        bulider.AppendLine("    public virtual void SetDataValue(ExcelRange cell, int row, int cloumn)");
        bulider.AppendLine("	{");
        bulider.AppendLine($"{setdataValue}");
        bulider.AppendLine("	}");
        bulider.AppendLine();

        bulider.AppendLine();
        bulider.AppendLine("    public override string ToString()");
        bulider.AppendLine("	{");
        bulider.AppendLine($"        return  $\"{{typeof({className})}}: {tostring}\";");
        bulider.AppendLine("	}");
        bulider.AppendLine();


        bulider.AppendLine("}");



        Debug.Log(bulider.ToString());

        return bulider.ToString();
    }
}

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值