//====================================
//描 述 : 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;
}
}