Unity版本 2019.4.9f1
准备工作
- 安装Excel的拓展库,百度网盘提取码1234
- 新建一个Plugins文件夹,将下载的拓展库放进去。
- 创建资源文件夹
开始扣代码
1. 创建基本数据类型
ExItem可以根据自己后期需要定义多个类型使用
using System.Collections.Generic;
using UnityEngine;
namespace Data
{
[System.Serializable]
public class ExItem
{
public uint itemId; // uint为无符号整型
// 可以自定义所需数据的类型
// public int itemID;
// public string itemName;
public List<string> itemData;
}
public class ItemManager : ScriptableObject
{
public ExItem[] dataArray;
}
public class ExCell
{
public string name;
public string info;
}
}
2. 创建地址类型
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExcelConfig
{
/// <summary>
/// 存放excel表文件夹的的路径
/// </summary>
public static readonly string excelPath = Application.dataPath + "/Resources/Config/Excel/";
/// <summary>
/// 存放Excel转化的Assest文件的文件夹路径
/// </summary>
public static readonly string assetPath = "Assets/Resources/Config/AssetsFile/";
/// <summary>
/// 存放Excel转化的xml文件的文件夹路径
/// </summary>
public static readonly string xmlPath = "Assets/Resources/Config/Xml/";
}
3.工具代码
using System.Collections.Generic;
using System.Data;
using System.IO;
using Excel;
using Data;
using System;
public class ExcelTool
{
static DataRowCollection ReadExcel(string filePath, ref int columnNum, ref int rowNum)
{
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
//Tables[0] 下标0表示excel文件中第一张表的数据
columnNum = result.Tables[0].Columns.Count;
rowNum = result.Tables[0].Rows.Count;
return result.Tables[0].Rows;
}
/// <summary>
/// 读取表数据,生成对应的数组
/// </summary>
/// <param name="filePath">excel文件全路径</param>
/// <returns>Item数组</returns>
public static ExItem[] CreateItemArrayWithExcel(string filePath)
{
//获得表数据
int columnNum = 0, rowNum = 0;
DataRowCollection excelData = ReadExcel(filePath, ref columnNum, ref rowNum);
//根据excel的定义,第二行开始才是数据
ExItem[] array = new ExItem[rowNum - 1];
for (int i = 1; i < rowNum; i++)
{
ExItem item = new ExItem();
//解析每列的数据
item.itemId = uint.Parse(excelData[i][0].ToString());
item.itemData = new List<string>();
for (int j = 0; j < columnNum; j++)
{
item.itemData.Add(Convert.ToString(excelData[i][j]));
}
array[i - 1] = item;
}
return array;
}
public static List<List<ExCell>> ReadExcelInfo(string filePath)
{
// 获取表格情况 columnNum竖列,rowNum横排
int columnNum = 0, rowNum = 0;
DataRowCollection excelData = ReadExcel(filePath, ref columnNum, ref rowNum);
// Debug.Log("表格情况:" + columnNum + "/" + rowNum);
List<List<ExCell>> list = new List<List<ExCell>>();
for (int i = 1; i < rowNum; i++)
{
List<ExCell> item = new List<ExCell>();
for (int j = 0; j < columnNum; j++)
{
ExCell excell = new ExCell();
excell.name = Convert.ToString(excelData[0][j]);
excell.info = Convert.ToString(excelData[i][j]);
// Debug.Log("ID:" + itemInfo.name + "/" + itemInfo.info);
item.Add(excell);
}
list.Add(item);
}
return list;
}
}
4.编辑器代码
新建Editor文件夹,代码需新建在Editor文件夹里
using Data;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEditor;
public class ExcelBuild : Editor
{
[MenuItem("ExcelBuild/ExcelToAsset")]
public static void Excel2Asset()
{
// 检测文件夹是否存在
if (Directory.Exists(ExcelConfig.excelPath))
{
//List<>
// 获取文件夹信息
DirectoryInfo direction = new DirectoryInfo(ExcelConfig.excelPath);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
for (int i = 0; i < files.Length; i++)
{
if (files[i].Name.EndsWith(".xlsx"))
{
ExportExcelToAsset(ExcelConfig.excelPath + files[i].Name, files[i].Name.Substring(0, files[i].Name.IndexOf('.')));
}
}
}
else
{
// 创建文件夹
Directory.CreateDirectory(ExcelConfig.excelPath);
// 给点提示
// throw new System.Exception("Excel文件夹为空");
}
// 刷新视图
AssetDatabase.Refresh();
}
public static void ExportExcelToAsset(string path, string name)
{
ItemManager manager = CreateInstance<ItemManager>();
// 赋值
manager.dataArray = ExcelTool.CreateItemArrayWithExcel(path);
// 确保文件是新的
if (File.Exists(ExcelConfig.assetPath + name + ".asset"))
{
File.Delete(ExcelConfig.assetPath + name + ".asset");
}
//asset文件的路径 要以"Assets/..."开始,否则会报错
string assetPath = string.Format("{0}{1}.asset", ExcelConfig.assetPath, name);
// Debug.Log("转化的数据:" + manager.dataArray.Length);
// 生成Asset文件
AssetDatabase.CreateAsset(manager, assetPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
[MenuItem("ExcelBuild/ExcelToXml")]
public static void Excel2Xml()
{
// 检测文件夹是否存在
if (Directory.Exists(ExcelConfig.excelPath))
{
//List<>
// 获取文件夹信息
DirectoryInfo direction = new DirectoryInfo(ExcelConfig.excelPath);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
for (int i = 0; i < files.Length; i++)
{
if (files[i].Name.EndsWith(".xlsx"))
{
ExportExcel2Xml(ExcelConfig.excelPath + files[i].Name, files[i].Name.Substring(0, files[i].Name.IndexOf('.')));
}
}
}
else
{
// 创建文件夹
Directory.CreateDirectory(ExcelConfig.excelPath);
}
// 刷新视图
AssetDatabase.Refresh();
}
public static void ExportExcel2Xml(string path, string name)
{
List<List<ExCell>> list = ExcelTool.ReadExcelInfo(path);
// Debug.Log("表格长度" + list.Count);
string xmlPath = ExcelConfig.xmlPath + "/" + name + ".xml";
// 文件夹不存在?
if (!File.Exists(ExcelConfig.xmlPath))
{
Directory.CreateDirectory(ExcelConfig.xmlPath);
// throw new System.Exception("Xml文件夹为空");
}
// 文件存在?
if (File.Exists(xmlPath))
{
File.Delete(xmlPath);
}
// 创建xml文件
XmlDocument xml = new XmlDocument();
// 创建最上一层的根节点
XmlElement root = xml.CreateElement("elements");
for (int i = 0; i < list.Count; i++)
{
// 创建每一行的子节点信息
XmlElement element = xml.CreateElement("element");
for (int j = 0; j < list[i].Count; j++)
{
// Debug.Log("cell数量" + list[i][j].name);
// 设置子节点的内容
element.SetAttribute(list[i][j].name, list[i][j].info);
}
// 添加到最上层节点下
root.AppendChild(element);
}
// 将根节点添加到xml里
xml.AppendChild(root);
// 保存xml文件
xml.Save(xmlPath);
}
}
工具栏效果
点击工具栏的ExcelBuild->ExcelToAsset
即可生成所需的Asset文件
点击工具栏的ExcelBuild->ExcelToXml
即可生成所需的Xml文件