大家好,又见面了,我是你们的朋友全栈君。
- 创建脚本文件,继承自EditorWindow
public class LocalizationTool : EditorWindow
- 添加至工具栏;
[MenuItem("Tools/LocalizationTool")]
- 实现操作界面;
代码如下:
private void OnGUI()
{
GUILayout.Space(15);
GUILayout.BeginHorizontal();
GUILayout.Label("Excel目录:", EditorStyles.boldLabel, GUILayout.Width(80));
GUILayout.TextField(excelPath);
if (GUILayout.Button("浏览", GUILayout.Width(50)))
{
SelectExcelPath();
}
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
GUILayout.Label("Json目录:", EditorStyles.boldLabel, GUILayout.Width(80));
GUILayout.TextField(jsonPath);
if (GUILayout.Button("浏览", GUILayout.Width(50)))
{
SelectJsonPath();
}
GUILayout.EndHorizontal();
GUILayout.Space(30);
GUILayout.BeginHorizontal();
GUILayout.Label("");
if (GUILayout.Button("Localization", GUILayout.Width(100)))
{
ExcelToJson();
}
GUILayout.Label("");
GUILayout.EndHorizontal();
}
- 实现Excel转Json;
private void ExcelToJson()
{
Debug.Log(excelPath);
if (!Directory.Exists(excelPath))
{
Debug.Log("路径不存在");
}
DirectoryInfo info = new DirectoryInfo(excelPath);
FileInfo[] files = info.GetFiles();
for (int i = 0; i < files.Length; i++)
{
bool b1 = files[i].Name.EndsWith(".xls");
bool b2 = files[i].Name.EndsWith(".xlsx");
bool b = b1 || b2;
if (File.Exists(files[i].FullName) && b)
{
var wk = WorkbookFactory.Create(files[i].FullName);
for (int j = 0; j < wk.NumberOfSheets; j++)
{
ISheet sheet = wk.GetSheetAt(j);
if (sheet.LastRowNum > 0)
{
var row_0 = sheet.GetRow(0);
if (row_0 != null && row_0.LastCellNum > 1)
{
for (int l = 0; l < row_0.LastCellNum - 1; l++)
{
var t = new Dictionary<string, object>();
var path = "";
var lst = new List<Dictionary<string, object>>();
for (int k = 1; k <= sheet.LastRowNum; k++)
{
var r = new Dictionary<string, object>();
IRow row = sheet.GetRow(k);
if (row != null)
{
r[row_0.GetCell(0).ToString()] = row.GetCell(0).ToString();
r["textContent"] = row.GetCell(l + 1).ToString();
path = row_0.GetCell(l + 1).ToString();
}
lst.Add(r);
}
t.Add("data", lst);
string output = JsonConvert.SerializeObject(t, Formatting.Indented);
File.WriteAllBytes(getTargetFilePath(jsonPath, Path.GetFileNameWithoutExtension(files[i].Name), path), Encoding.UTF8.GetBytes(output));
}
}
}
}
}
}
}
private static string getTargetFilePath(string filePath, string fileName, string fileType)
{
var b1 = Path.GetFileNameWithoutExtension(fileName) + "_" + fileType;
filePath = Path.Combine(filePath, string.Format("{0}.json", b1));
return filePath;
}
Excel文件如下:
生成的json文件如下:
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/139992.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...