unity 中excel转json插件

Posted 丛小胖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity 中excel转json插件相关的知识,希望对你有一定的参考价值。

1 工具简介

将策划配置的excel转换成程序使用json文件。方便策划是excel的功能。

2文件的放置和生成

需要将excle文件放置到项目中的Excel文件夹下面。

生成的文件会在Res/Config文件夹下面

生成json文件只需要点击Tools下的ExcelTools就可以了

3 excel文件的格式

第一行是说明,不具有实际意义

第二行为属性的名字,json文件的key值。不能使用数字开头,特殊符号开头,不能使用程序内的关键字,如:string,int。

第三行是程序内使用的类型,支持的类型有 string  int  float  double  bool。

bool中fasle,0,空白 都代表否的意思,填写其他值代表为真

生成的接json文件的名字是以表命中(#文件名#) #号包裹的名字位主的,如果表名不存在#号,则该表不导出。示例如下图:

4 注意事项

1. excel文件名中不能存在空格或特殊符号

2. excel后缀只支持xlsx,并且需要确保后缀小写,不能使用大写

3. 导出的文件名确定后不要轻易修改,修改需要和程序确认(#文件名#)

4. 添加。删除。修改字段时,请和程序确定,防止游戏内逻辑出错

5. json中需要转换的数据结构由程序自行创建

6. 每次生成会清理config文件,重新从excel生成json文件。请不要手动修改生成后的json文件。确保excel文件的正确定。不要config文件夹下面放置其他文件

7. 使用工具的时候需要关闭excel文件

using UnityEngine;
using System.IO;
using System.Linq;

/// <summary>
///  @ 2017.12.25
/// 功能:通用静态方法
/// </summary>


public class GameUtility

    public const string AssetsFolderName = "Assets";

    public static string FormatToUnityPath(string path)
    
        return path.Replace("\\\\", "/");
    

    public static string FormatToSysFilePath(string path)
    
        return path.Replace("/", "\\\\");
    

    public static string FullPathToAssetPath(string full_path)
    
        full_path = FormatToUnityPath(full_path);
        if (!full_path.StartsWith(Application.dataPath))
        
            return null;
        
        string ret_path = full_path.Replace(Application.dataPath, "");
        return AssetsFolderName + ret_path;
    

    public static string GetFileExtension(string path)
    
        return Path.GetExtension(path).ToLower();
    

    public static string[] GetSpecifyFilesInFolder(string path, string[] extensions = null, bool exclude = false)
    
        if (string.IsNullOrEmpty(path))
        
            return null;
        

        if (extensions == null)
        
            return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
        
        else if (exclude)
        
            return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
                .Where(f => !extensions.Contains(GetFileExtension(f))).ToArray();
        
        else
        
            return Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
                .Where(f => extensions.Contains(GetFileExtension(f))).ToArray();
        
    

    public static string[] GetSpecifyFilesInFolder(string path, string pattern)
    
        if (string.IsNullOrEmpty(path))
        
            return null;
        

        return Directory.GetFiles(path, pattern, SearchOption.AllDirectories);
    

    public static string[] GetAllFilesInFolder(string path)
    
        return GetSpecifyFilesInFolder(path);
    

    public static string[] GetAllDirsInFolder(string path)
    
        return Directory.GetDirectories(path, "*", SearchOption.AllDirectories);
    

    public static void CheckFileAndCreateDirWhenNeeded(string filePath)
    
        if (string.IsNullOrEmpty(filePath))
        
            return;
        

        FileInfo file_info = new FileInfo(filePath);
        DirectoryInfo dir_info = file_info.Directory;
        if (!dir_info.Exists)
        
            Directory.CreateDirectory(dir_info.FullName);
        
    

    public static void CheckDirAndCreateWhenNeeded(string folderPath)
    
        if (string.IsNullOrEmpty(folderPath))
        
            return;
        

        if (!Directory.Exists(folderPath))
        
            Directory.CreateDirectory(folderPath);
        
    

    public static bool SafeWriteAllBytes(string outFile, byte[] outBytes)
    
        try
        
            if (string.IsNullOrEmpty(outFile))
            
                return false;
            

            CheckFileAndCreateDirWhenNeeded(outFile);
            if (File.Exists(outFile))
            
                File.SetAttributes(outFile, FileAttributes.Normal);
            
            File.WriteAllBytes(outFile, outBytes);
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeWriteAllBytes failed! path = 0 with err = 1", outFile, ex.Message));
            return false;
        
    

    public static bool SafeWriteAllLines(string outFile, string[] outLines)
    
        try
        
            if (string.IsNullOrEmpty(outFile))
            
                return false;
            

            CheckFileAndCreateDirWhenNeeded(outFile);
            if (File.Exists(outFile))
            
                File.SetAttributes(outFile, FileAttributes.Normal);
            
            File.WriteAllLines(outFile, outLines);
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeWriteAllLines failed! path = 0 with err = 1", outFile, ex.Message));
            return false;
        
    

    public static bool SafeWriteAllText(string outFile, string text)
    
        try
        
            if (string.IsNullOrEmpty(outFile))
            
                return false;
            

            CheckFileAndCreateDirWhenNeeded(outFile);
            if (File.Exists(outFile))
            
                File.SetAttributes(outFile, FileAttributes.Normal);
            
            File.WriteAllText(outFile, text);
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeWriteAllText failed! path = 0 with err = 1", outFile, ex.Message));
            return false;
        
    

    public static byte[] SafeReadAllBytes(string inFile)
    
        try
        
            if (string.IsNullOrEmpty(inFile))
            
                return null;
            

            if (!File.Exists(inFile))
            
                return null;
            

            File.SetAttributes(inFile, FileAttributes.Normal);
            return File.ReadAllBytes(inFile);
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeReadAllBytes failed! path = 0 with err = 1", inFile, ex.Message));
            return null;
        
    

    public static string[] SafeReadAllLines(string inFile)
    
        try
        
            if (string.IsNullOrEmpty(inFile))
            
                return null;
            

            if (!File.Exists(inFile))
            
                return null;
            

            File.SetAttributes(inFile, FileAttributes.Normal);
            return File.ReadAllLines(inFile);
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeReadAllLines failed! path = 0 with err = 1", inFile, ex.Message));
            return null;
        
    

    public static string SafeReadAllText(string inFile)
    
        try
        
            if (string.IsNullOrEmpty(inFile))
            
                return null;
            

            if (!File.Exists(inFile))
            
                return null;
            

            File.SetAttributes(inFile, FileAttributes.Normal);
            return File.ReadAllText(inFile);
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeReadAllText failed! path = 0 with err = 1", inFile, ex.Message));
            return null;
        
    

    public static void DeleteDirectory(string dirPath)
    
        string[] files = Directory.GetFiles(dirPath);
        string[] dirs = Directory.GetDirectories(dirPath);

        foreach (string file in files)
        
            File.SetAttributes(file, FileAttributes.Normal);
            File.Delete(file);
        

        foreach (string dir in dirs)
        
            DeleteDirectory(dir);
        

        Directory.Delete(dirPath, false);
    

    public static bool SafeClearDir(string folderPath)
    
        try
        
            if (string.IsNullOrEmpty(folderPath))
            
                return true;
            

            if (Directory.Exists(folderPath))
            
                DeleteDirectory(folderPath);
            
            Directory.CreateDirectory(folderPath);
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeClearDir failed! path = 0 with err = 1", folderPath, ex.Message));
            return false;
        
    

    public static bool SafeDeleteDir(string folderPath)
    
        try
        
            if (string.IsNullOrEmpty(folderPath))
            
                return true;
            

            if (Directory.Exists(folderPath))
            
                DeleteDirectory(folderPath);
            
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeDeleteDir failed! path = 0 with err: 1", folderPath, ex.Message));
            return false;
        
    

    public static bool SafeDeleteFile(string filePath)
    
        try
        
            if (string.IsNullOrEmpty(filePath))
            
                return true;
            

            if (!File.Exists(filePath))
            
                return true;
            
            File.SetAttributes(filePath, FileAttributes.Normal);
            File.Delete(filePath);
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeDeleteFile failed! path = 0 with err: 1", filePath, ex.Message));
            return false;
        
    

    public static bool SafeRenameFile(string sourceFileName, string destFileName)
    
        try
        
            if (string.IsNullOrEmpty(sourceFileName))
            
                return false;
            

            if (!File.Exists(sourceFileName))
            
                return true;
            
            SafeDeleteFile(destFileName);
            File.SetAttributes(sourceFileName, FileAttributes.Normal);
            File.Move(sourceFileName, destFileName);
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeRenameFile failed! path = 0 with err: 1", sourceFileName, ex.Message));
            return false;
        
    

    public static bool SafeCopyFile(string fromFile, string toFile)
    
        try
        
            if (string.IsNullOrEmpty(fromFile))
            
                return false;
            

            if (!File.Exists(fromFile))
            
                return false;
            
            CheckFileAndCreateDirWhenNeeded(toFile);
            SafeDeleteFile(toFile);
            File.Copy(fromFile, toFile, true);
            return true;
        
        catch (System.Exception ex)
        
            Debug.LogError(string.Format("SafeCopyFile failed! formFile = 0, toFile = 1, with err = 2",
                fromFile, toFile, ex.Message));
            return false;
        
    

下载链接: https://pan.baidu.com/s/1uOlQg6qcn4gFH16aDx8B-Q?pwd=w23u 提取码: w23u

Unity3D日常开发Unity3D中实现Excel转XMLJsonCSV文件

推荐阅读

大家好,我是佛系工程师☆恬静的小魔龙☆,不定时更新Unity开发技巧,觉得有用记得一键三连哦。

一、前言

在日常开发中,可能会遇到将Excel表格转成其他格式文件的情况。

比如ExcelXML、Json、CSV文件,那么就来学习一下如何实现吧。

二、正文

2-1、导入读取Excel所需要的dll文件

读取Excel文件,需要导入一些dll文件,才能正常的读取、创建Excell文件:

这些文件,我放到了CSDN按需下载:
https://download.csdn.net/download/q764424567/21046571

将下载后的dll文件放到Plugins文件夹内:

2-2、Excel文件转成Json、XML、CSV文件

在Project视图中,进入Scripts文件夹,新建一个Editor文件夹,然后在Editor文件内右击→Create→C# Script新建脚本, 命名为ExcelUtility,双击修改代码:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Excel;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System;

public class ExcelUtility

    /// <summary>
    /// 表格数据集合
    /// </summary>
    private DataSet mResultSet;

    /// <summary>
    /// 读取表数据
    /// </summary>
    /// <param name="excelFile">Excel file.</param>
    public ExcelUtility(string excelFile)
    
        FileStream mStream = File.Open(excelFile, FileMode.Open, FileAccess.Read);
        IExcelDataReader mExcelReader = ExcelReaderFactory.CreateOpenXmlReader(mStream);
        mResultSet = mExcelReader.AsDataSet();
    

    /// <summary>
    /// 转换为Json格式文件
    /// </summary>
    /// <param name="JsonPath">Json文件路径</param>
    /// <param name="Header">表头行数</param>
    public void ConvertToJson(string JsonPath, Encoding encoding)
    
        //判断Excel文件中是否存在数据表
        if (mResultSet.Tables.Count < 1)
            return;

        //默认读取第一个数据表
        DataTable mSheet = mResultSet.Tables[0];

        //判断数据表内是否存在数据
        if (mSheet.Rows.Count < 1)
            return;

        //读取数据表行数和列数
        int rowCount = mSheet.Rows.Count;
        int colCount = mSheet.Columns.Count;

        //准备一个列表存储整个表的数据
        List<Dictionary<string, object>> table = new List<Dictionary<string, object>>();

        //读取数据
        for (int i = 1; i < rowCount; i++)
        
            //准备一个字典存储每一行的数据
            Dictionary<string, object> row = new Dictionary<string, object>();
            for (int j = 0; j < colCount; j++)
            
                //读取第1行数据作为表头字段
                string field = mSheet.Rows[0][j].ToString();
                //Key-Value对应
                row[field] = mSheet.Rows[i][j];
            

            //添加到表数据中
            table.Add(row);
        

        //生成Json字符串
        string json = JsonConvert.SerializeObject(table, Newtonsoft.Json.Formatting.Indented);
        //写入文件
        using (FileStream fileStream = new FileStream(JsonPath, FileMode.Create, FileAccess.Write))
        
            using (TextWriter textWriter = new StreamWriter(fileStream, encoding))
            
                textWriter.Write(json);
            
        
    

    /// <summary>
    /// 转换为CSV格式文件
    /// </summary>
    public void ConvertToCSV(string CSVPath, Encoding encoding)
    
        //判断Excel文件中是否存在数据表
        if (mResultSet.Tables.Count < 1)
            return;

        //默认读取第一个数据表
        DataTable mSheet = mResultSet.Tables[0];

        //判断数据表内是否存在数据
        if (mSheet.Rows.Count < 1)
            return;

        //读取数据表行数和列数
        int rowCount = mSheet.Rows.Count;
        int colCount = mSheet.Columns.Count;

        //创建一个StringBuilder存储数据
        StringBuilder stringBuilder = new StringBuilder();

        //读取数据
        for (int i = 0; i < rowCount; i++)
        
            for (int j = 0; j < colCount; j++)
            
                //使用","分割每一个数值
                stringBuilder.Append(mSheet.Rows[i][j] + ",");
            
            //使用换行符分割每一行
            stringBuilder.Append("\\r\\n");
        

        //写入文件
        using (FileStream fileStream = new FileStream(CSVPath, FileMode.Create, FileAccess.Write))
        
            using (TextWriter textWriter = new StreamWriter(fileStream, encoding))
            
                textWriter.Write(stringBuilder.ToString());
            
        

    

    /// <summary>
    /// 转换为Xml格式文件
    /// </summary>
    public void ConvertToXml(string XmlFile)
    
        //判断Excel文件中是否存在数据表
        if (mResultSet.Tables.Count < 1)
            return;

        //默认读取第一个数据表
        DataTable mSheet = mResultSet.Tables[0];

        //判断数据表内是否存在数据
        if (mSheet.Rows.Count < 1)
            return;

        //读取数据表行数和列数
        int rowCount = mSheet.Rows.Count;
        int colCount = mSheet.Columns.Count;

        //创建一个StringBuilder存储数据
        StringBuilder stringBuilder = new StringBuilder();
        //创建Xml文件头
        stringBuilder.Append("<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?>");
        stringBuilder.Append("\\r\\n");
        //创建根节点
        stringBuilder.Append("<Table>");
        stringBuilder.Append("\\r\\n");
        //读取数据
        for (int i = 1; i < rowCount; i++)
        
            //创建子节点
            stringBuilder.Append("  <Row>");
            stringBuilder.Append("\\r\\n");
            for (int j = 0; j < colCount; j++)
            
                stringBuilder.Append("   <" + mSheet.Rows[0][j].ToString() + ">");
                stringBuilder.Append(mSheet.Rows[i][j].ToString());
                stringBuilder.Append("</" + mSheet.Rows[0][j].ToString() + ">");
                stringBuilder.Append("\\r\\n");
            
            //使用换行符分割每一行
            stringBuilder.Append("  </Row>");
            stringBuilder.Append("\\r\\n");
        
        //闭合标签
        stringBuilder.Append("</Table>");
        //写入文件
        using (FileStream fileStream = new FileStream(XmlFile, FileMode.Create, FileAccess.Write))
        
            using (TextWriter textWriter = new StreamWriter(fileStream, Encoding.GetEncoding("utf-8")))
            
                textWriter.Write(stringBuilder.ToString());
            
        
    

2-3、工具使用方法

使用方法:制作一个简单的编辑器工具,来快捷使用:


在Editor文件夹内,再新建一个脚本,命名为ExcelTools.cs,双击修改代码:

using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Text;

public class ExcelTools : EditorWindow

	/// <summary>
	/// 当前编辑器窗口实例
	/// </summary>
	private static ExcelTools instance;

	/// <summary>
	/// Excel文件列表
	/// </summary>
	private static List<string> excelList;

	/// <summary>
	/// 项目根路径	
	/// </summary>
	private static string pathRoot;

	/// <summary>
	/// 滚动窗口初始位置
	/// </summary>
	private static Vector2 scrollPos;

	/// <summary>
	/// 输出格式索引
	/// </summary>
	private static int indexOfFormat=0;

	/// <summary>
	/// 输出格式
	/// </summary>
	private static string[] formatOption=new string[]"JSON","CSV","XML";

	/// <summary>
	/// 编码索引
	/// </summary>
	private static int indexOfEncoding=0;

	/// <summary>
	/// 编码选项
	/// </summary>
	private static string[] encodingOption=new string[]"UTF-8","GB2312";

	/// <summary>
	/// 是否保留原始文件
	/// </summary>
	private static bool keepSource=true;

	/// <summary>
	/// 显示当前窗口	
	/// </summary>
	[MenuItem("Plugins/ExcelTools")]
	static void ShowExcelTools()
	
		Init();
		//加载Excel文件
		LoadExcel();
		instance.Show();
	

	void OnGUI()
	
		DrawOptions();
		DrawExport();
	

	/// <summary>
	/// 绘制插件界面配置项
	/// </summary>
	private void DrawOptions()
	
		GUILayout.BeginHorizontal();
		EditorGUILayout.LabelField("请选择格式类型:",GUILayout.Width(85));
		indexOfFormat=EditorGUILayout.Popup(indexOfFormat,formatOption,GUILayout.Width(125));
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		EditorGUILayout.LabelField("请选择编码类型:",GUILayout.Width(85));
		indexOfEncoding=EditorGUILayout.Popup(indexOfEncoding,encodingOption,GUILayout.Width(125));
		GUILayout.EndHorizontal();

		keepSource=GUILayout.Toggle(keepSource,"保留Excel源文件");
	

	/// <summary>
	/// 绘制插件界面输出项
	/// </summary>
	private void DrawExport()
	
		if(excelList==null) return;
		if(excelList.Count<1)
		
			EditorGUILayout.LabelField("目前没有Excel文件被选中哦!");
		
		else
		
			EditorGUILayout.LabelField("下列项目将被转换为" + formatOption[indexOfFormat] + ":");
			GUILayout.BeginVertical();
			scrollPos=GUILayout.BeginScrollView(scrollPos,false,true,GUILayout.Height(150));
			foreach(string s in excelList)
			
				GUILayout.BeginHorizontal();
				GUILayout.Toggle(true,s);
				GUILayout.EndHorizontal();
			
			GUILayout.EndScrollView();
			GUILayout.EndVertical();

			//输出
			if(GUILayout.Button("转换"))
			
				Convert();
			
		
	

	/// <summary>
	/// 转换Excel文件
	/// </summary>
	private static void Convert()
	
		foreach(string assetsPath in excelList)
		
			//获取Excel文件的绝对路径
			string excelPath=pathRoot + "/" + assetsPath;
			//构造Excel工具类
			ExcelUtility excel=new ExcelUtility(excelPath);

			//判断编码类型
			Encoding encoding=null;
			if(indexOfEncoding==0)
				encoding=Encoding.GetEncoding("utf-8");
			else if(indexOfEncoding==1)
				encoding=Encoding.GetEncoding("gb2312");
			

			//判断输出类型
			string output="";
			if(indexOfFormat==0)
				output=excelPath.Replace(".xlsx",".json");
				excel.ConvertToJson(output,encoding);
			else if(indexOfFormat==1)
				output=excelPath.Replace(".xlsx",".csv");
				excel.ConvertToCSV(output,encoding);
			else if(indexOfFormat==2)
				output=excelPath.Replace(".xlsx",".xml");
				excel.ConvertToXml(output);
			

			//判断是否保留源文件
			if(!keepSource)
			
				FileUtil.DeleteFileOrDirectory(excelPath);
			

			//刷新本地资源
			AssetDatabase.Refresh();
		

		//转换完后关闭插件
		//这样做是为了解决窗口
		//再次点击时路径错误的Bug
		instance.Close();

	

	/// <summary>
	/// 加载Excel
	/// </summary>
	private static void LoadExcel()
	
		if(excelList==null) excelList=new List<string>();
		excelList.Clear();
		//获取选中的对象
		object[] selection=(object[])Selection.objects;
		//判断是否有对象被选中
		if(selection.Length==0)
			return;
		//遍历每一个对象判断不是Excel文件
		foreach(Object obj in selection)
		
			string objPath=AssetDatabase.GetAssetPath(obj);
			if(objPath.EndsWith(".xlsx"))
			
				excelList.Add(objPath);
			
		
	

	private static void Init()
	
		//获取当前实例
		instance=EditorWindow.GetWindow<ExcelTools>()Unity3D日常开发Unity3D中实现Excel转XMLJsonCSV文件

Unity3D编辑器扩展Unity3D中实现Excel转XMLJsonCSV文件

前端 XLSX 插件包 读取excel文件转成json数据给接口

Laya---数据读取--- Excel转Json

Laya---数据读取--- Excel转Json

excel转json的步骤介绍