using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
public class ExcelHelp
{
private const string ExcelPath = "../ServerExcel";
public static void StartWriteExcel<T>(string name, List<T> str)
{
return;
if (str.Count <= 0) return;
string path = Path.Combine(ExcelPath, name + ".xlsm");
if (!Directory.Exists(ExcelPath))
{
Directory.CreateDirectory(ExcelPath);
}
if (File.Exists(path))
{
File.Delete(path);
}
List<FieldInfo> temp = GetColumnHead<T>(str[0]);
ISheet sheet = null;
IRow row = null;
ICell cell = null;
IWorkbook workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet("Sheet0");//創建一個名稱爲Sheet0的表
row = sheet.CreateRow(0);
int index = -1;
//excel第一行設爲列頭
int thisIndx = 0;
for (int c = 0; c < temp.Count; c++, thisIndx++)
{
if (thisIndx != c && c == temp.Count - 1)
break;
if (temp[thisIndx].FieldType == typeof(Vector3))
{
index = c;
thisIndx++;
}
cell = row.CreateCell(c);
cell.SetCellValue(temp[thisIndx].Name);
}
if (index != -1)
{
cell = row.CreateCell(temp.Count - 1);
cell.SetCellValue("PostionX");
cell = row.CreateCell(temp.Count);
cell.SetCellValue("PostionY");
cell = row.CreateCell(temp.Count + 1);
cell.SetCellValue("PostionZ");
}
//設置每行每列的單元格,
for (int i = 0; i < str.Count; i++)
{
row = sheet.CreateRow(i + 1);
thisIndx = 0;
for (int j = 0; j < temp.Count; j++, thisIndx++)
{
if (thisIndx != j && j == temp.Count - 1)
break;
if (j == index)
{
thisIndx++;
}
cell = row.CreateCell(j);//excel第二行開始寫入數據
cell.SetCellValue(temp[thisIndx].GetValue(str[i]).ToString());
}
if (index != -1)
{
Vector3 tempPos = (Vector3)temp[index].GetValue(str[i]);
cell = row.CreateCell(temp.Count - 1);
cell.SetCellValue(tempPos.x.ToString());
cell = row.CreateCell(temp.Count);
cell.SetCellValue(tempPos.y.ToString());
cell = row.CreateCell(temp.Count + 1);
cell.SetCellValue(tempPos.z.ToString());
}
}
File.Create(path).Dispose();
using (FileStream fs = File.OpenWrite(path))
{
workbook.Write(fs);//向打開的這個xls文件中寫入數據
Debug.Log(name + "導出.xlsm完成");
}
}
private static List<FieldInfo> GetColumnHead<T>(T type)
{
List<FieldInfo> tempList = new List<FieldInfo>();
FieldInfo[] minfos = type.GetType().GetFields();
tempList = minfos.ToList();
return tempList;
}
}
unityEditor將類屬性寫入xlm
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.