2025-04-21 09:59:18 +08:00

97 lines
2.8 KiB
C#

using Aspose.Words;
using Aspose.Words.Replacing;
using UnityEngine;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
public class AsposeHelper : MonoBehaviour
{
//public static void Writer(string json, Action callback = null)
//{
// // 加载Word文档
// Document doc = new Document(Global.reportDemoPath);
// JObject jObject = JObject.Parse(json);
// foreach (JProperty property in jObject.Properties())
// {
// string key = property.Name;
// string value = property.Value.ToString();
// doc.Range.Replace($"{{{key}}}", $"{value}", new FindReplaceOptions());
// }
// string filePath = ChinarFileController.SaveProject(Path.GetFileName(Global.reportDemoPath).Split('.')[1]);
// if (string.IsNullOrEmpty(filePath) == false)
// {
// doc.Save(filePath);
// }
// callback?.Invoke();
// // 替换文本
// //SaveWithDialog(doc, callback);
// //Debug.Log("文档处理完成,新文档已保存到: " + outputFilePath);
//}
public static void Writer(string json, Action callback = null)
{
// 加载Word文档
Document doc = new Document(Global.reportDemoPath);
JToken jToken = JToken.Parse(json);
TraverseAndReplace(jToken, doc);
string filePath = ChinarFileController.SaveProject(Path.GetFileName(Global.reportDemoPath).Split('.')[1]);
if (!string.IsNullOrEmpty(filePath))
{
doc.Save(filePath);
}
callback?.Invoke();
}
private static void TraverseAndReplace(JToken jToken, Document doc)
{
if (jToken.Type == JTokenType.Object)
{
foreach (JProperty property in ((JObject)jToken).Properties())
{
if (property.Value.Type == JTokenType.Object || property.Value.Type == JTokenType.Array)
{
TraverseAndReplace(property.Value, doc);
}
else
{
string key = property.Name;
string value = property.Value.ToString();
doc.Range.Replace($"{{{key}}}", $"{value}", new FindReplaceOptions());
}
}
}
else if (jToken.Type == JTokenType.Array)
{
foreach (JToken item in jToken)
{
TraverseAndReplace(item, doc);
}
}
}
//private static void SaveWithDialog(Document doc, Action<DialogResult> callback)
//{
// SaveFileDialog dialog = new SaveFileDialog();
// dialog.Filter = "Word文档|*.docx";
// var result = dialog.ShowDialog();
// if (result == DialogResult.OK)
// {
// doc.Save(dialog.FileName);
// }
// callback?.Invoke(result);
//}
}