C# => Excel

本文介绍了一种使用C#将代码数据转换为Excel文件的方法,通过Unity编辑器实现,适用于游戏开发中数据管理和导出需求。代码示例展示了如何自动生成包含字段中文描述、英文名称及类型的工作表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//====================================
//描 述 : C# => Excel
//作 者 :  
//创建时间 :2018/10/12 10:27:12  
//版 本 :  
// ===============================================
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;

public class ConvertCodeToExcel : Editor {

    [MenuItem("Test/Code => Excel")]
    public static void  TestCreatExcel() {
        IWorkbook book = new HSSFWorkbook();
        CreatSheet(book, typeof(ExcelInfo));
        SaveExcel(book);
    }

    private static void CreatSheet(IWorkbook book, Type type){
        ISheet sheet = book.CreateSheet(type.Name);
        IRow chsNameRow = sheet.CreateRow(0);
        IRow engNameRow = sheet.CreateRow(1);
        IRow typeNameRow = sheet.CreateRow(2);

        FieldInfo[] fieldInfos = type.GetFields();
        if (fieldInfos.Length == 0)
            fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

        for (int i = 0; i < fieldInfos.Length; i++){
            FieldInfo fieldInfo = fieldInfos[i];
            Type fieldType = fieldInfo.FieldType;

            string chsName = "";
            for (int j = 0; j < fieldInfo.GetCustomAttributes(typeof(ChsAttr), false).Length; j++)
            {
                ChsAttr attr = fieldInfo.GetCustomAttributes(typeof(ChsAttr), false)[j] as ChsAttr;
                chsName = attr.description;
            }
            string engName = fieldInfo.Name;
            string typeName = fieldType.Name;

            chsNameRow.CreateCell(i).SetCellValue(chsName);
            engNameRow.CreateCell(i).SetCellValue(engName);
            typeNameRow.CreateCell(i).SetCellValue(typeName);

        }
    }

    private static void SaveExcel(IWorkbook book) {
        string path = "C:/Users/Administrator/Desktop/Test.xls";
        FileStream stream = null;
        try
        {
            if (File.Exists(path)) File.Delete(path);
            stream = File.OpenWrite(path);
            book.Write(stream);
            stream.Close();
        }
        catch {
            if (stream != null)
            {
                stream.Close();
            }
        }
    }
}


public class ExcelInfo {

    [ChsAttr("id")]
    public int id;
    [ChsAttr("名字")]
    public string name;
    [ChsAttr("数量")]
    public int number;

}


public class ChsAttr : PropertyAttribute
{
    public readonly string description;
    public ChsAttr(string des)
    {
        description = des;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值