using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Excel;
using System.IO;
using Assets.Scripts;
using System;
public static class ExcelWorker
{
public static List<T> ReadFromExcel<T>(this List<T> current, string excel_name = "", string sheet_name = "") where T : ExcelData, new()
{
if (!File.Exists(Application.streamingAssetsPath + "/" + excel_name))
{
Debug.Log("文件" + Application.streamingAssetsPath + "/" + excel_name + "不存在");
return current;
}
using (var fs = File.Open(Application.streamingAssetsPath + "/" + excel_name, FileMode.Open, FileAccess.Read))
{
using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs))
{
var table = excelReader.AsDataSet().Tables[sheet_name];
var fields = typeof(T).GetFields();
int rowCount = table.Rows.Count;
int columnCount = table.Columns.Count;
/// 第一行为变量名称
var variableNameList = new List<string>();
for (int i = 0; i < columnCount; i++)
{
variableNameList.Add(table.Rows[0][i].ToString());
// Debug.Log("列名:" + table.Rows[0][i].ToString());
}
for (int i = 1; i < rowCount; i++)
{
var item = new T();
var row = table.Rows[i];
for (int j = 0; j < fields.Length; j++)
{
var field = fields[j];
var index = variableNameList.IndexOf(field.Name);
if (index < 0)
{
Debug.LogError(string.Format("Excel表格{0}中,无法找到{1}字段", typeof(T).ToString(), field.Name));
}
else
{
field.SetValue(item, Convert.ChangeType(row[j], field.FieldType));
}
}
current.Add(item);
}
}
Debug.Log(string.Format("{0}_{1}:读出成功!", excel_name, sheet_name));
}
return current;
}
}
public class TestExcel : MonoBehaviour {
// Use this for initialization
void Start() {
FileStream stream = File.Open(Application.streamingAssetsPath + "/test.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
List<ThoughtData> excelDatas = new List<ThoughtData>();
excelDatas = ExcelWorker.ReadFromExcel<ThoughtData>(excelDatas, "test.xlsx", "Sheet1");
excelReader.Close();
}
// Update is called once per frame
void Update () {
}
}