The core code is as follows
using System.Collections.Generic;
using System.IO;
using NPOI.XWPF.UserModel;
using UnityEngine;
using Debug = UnityEngine.Debug;
/// <summary>
/// NPOI库的桥接代码辅助器
/// </summary>
public static class NPOIHelper
{
#region docx
/// <summary>
/// 通过识别模板中的关键字,进行图文替换
/// </summary>
public static void ReplaceByKeywords(List<OutputConfigData> datas, string templatePath, string outputPath)
{
if (!File.Exists(templatePath))
{
Debug.Log($"> output list word template cant find");
return;
}
FileStream fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read);
XWPFDocument doc = new XWPFDocument(fs);
foreach (var para in doc.Paragraphs)
{
Replace(para, datas);
}
foreach (var table in doc.Tables)
{
foreach (var row in table.Rows)
{
foreach (var cell in row.GetTableCells())
{
Replace(cell.Paragraphs[0], datas);
}
}
}
FileStream output = new FileStream(outputPath, FileMode.Create);
doc.Write(output);
fs.Close();
fs.Dispose();
output.Close();
output.Dispose();
}
/// <summary>
/// 替换模板内容
/// </summary>
/// <param name="paragraph"></param>
/// <param name="datas"></param>
static void Replace(XWPFParagraph paragraph, List<OutputConfigData> datas)
{
string oldText = paragraph.ParagraphText;
if (string.IsNullOrEmpty(oldText))
{
return;
}
foreach (var data in datas)
{
string newText = string.Empty;
if (oldText.Contains(data.Key))
{
if (data.Type == OutputConfigType.Text)
{
newText = oldText.Replace(data.Key, data.Value);
// 文本内容替换
paragraph.ReplaceText(oldText, newText);
}
else if(data.Type == OutputConfigType.Picture)
{
// 先把标识的文本替换为empty
paragraph.ReplaceText(oldText, newText);
using FileStream fs = new FileStream(data.Path, FileMode.Open, FileAccess.Read);
// 再去添加为图片
paragraph.Runs[0].AddPicture(fs, (int)PictureType.PNG, Path.GetFileName(data.Path), data.Width,
data.Height);
}
}
}
}
#endregion
}