irc-netcore-api/IRaCIS.Core.Application/Helper/NpoiWordHelper.cs

171 lines
5.0 KiB
C#

using IRaCIS.Core.Application.Helper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;
using System.Collections;
using System.Reflection;
namespace IRaCIS.Core.Application.Service;
public static class NpoiWordHelper
{
public static async Task<IActionResult> TemplateExportWordAsync(string code, object data, IRepository<CommonDocument>? _commonDocumentRepository, IWebHostEnvironment _hostEnvironment)
{
//var (physicalPath, fileNmae) = await FileStoreHelper.GetCommonDocPhysicalFilePathAsync(_hostEnvironment, _commonDocumentRepository, code);
var physicalPath = code;
using (FileStream stream = File.OpenRead(physicalPath))
{
XWPFDocument doc = new XWPFDocument(stream);
//遍历段落
foreach (var para in doc.Paragraphs)
{
ReplaceKey(para, data);
}
//遍历表格
var tables = doc.Tables;
foreach (var table in tables)
{
//ReplaceTableKey(table, data, "Data");
}
foreach (var table in tables)
{
foreach (var row in table.Rows)
{
foreach (var cell in row.GetTableCells())
{
foreach (var para in cell.Paragraphs)
{
ReplaceKey(para, data);
}
}
}
}
FileStream out1 = new FileStream("table.docx", FileMode.Create);
doc.Write(out1);
out1.Close();
return new FileStreamResult(stream, "application/msword")
{
FileDownloadName = $"replaced_{DateTime.Now.ToString("yyyyMMddHHmmss")}.docx"
};
}
}
private static void ReplaceKey(XWPFParagraph para, object model)
{
string text = para.ParagraphText;
Type t = model.GetType();
PropertyInfo[] pi = t.GetProperties();
foreach (PropertyInfo p in pi)
{
//$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一
if (text.Contains("$" + p.Name + "$"))
{
text = text.Replace("$" + p.Name + "$", p.GetValue(model)?.ToString());
}
}
//var runs = para.Runs;
//string styleid = para.Style;
//for (int i = 0; i < runs.Count; i++)
//{
// var run = runs[i];
// text = run.ToString();
// Type t = model.GetType();
// PropertyInfo[] pi = t.GetProperties();
// foreach (PropertyInfo p in pi)
// {
// //$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一
// if (text.Contains("$" + p.Name + "$"))
// {
// text = text.Replace("$" + p.Name + "$", p.GetValue(model)?.ToString());
// }
// }
// runs[i].SetText(text, 0);
//}
}
/// <summary>
/// 替换表格Key
/// </summary>
/// <param name="table"></param>
/// <param name="list"></param>
/// <param name="field"></param>
private static void ReplaceTableKey(XWPFTable table, IList list, String field)
{
List<XWPFParagraph> paras = new List<XWPFParagraph>();
// 获取最后一行数据,最后一行设置值
Int32 iLastRowIndex = 0;
for (int iIndex = 0; iIndex < table.Rows.Count; iIndex++)
{
if (iIndex == table.Rows.Count - 1)
{
iLastRowIndex = iIndex;
foreach (var cell in table.Rows[iIndex].GetTableCells())
{
foreach (var para in cell.Paragraphs)
{
paras.Add(para);
}
}
}
}
// 删除最后一行
table.RemoveRow(iLastRowIndex);
for (int iIndex = 0; iIndex < list.Count; iIndex++)
{
object data = list[iIndex];
Type t = data.GetType();
PropertyInfo[] pi = t.GetProperties();
// 表增加行
XWPFTableRow m_row = table.CreateRow();
CT_Row m_NewRow = new CT_Row();
String text = String.Empty;
Int32 jIndex = 0;
paras.ForEach(para =>
{
text = para.ParagraphText;
foreach (PropertyInfo p in pi)
{
if (text.Contains("$" + field + "." + p.Name + "$"))
{
m_row.GetCell(jIndex).SetText(p.GetValue(data, null).ToString());
}
}
jIndex++;
});
m_row = new XWPFTableRow(m_NewRow, table);
table.AddRow(m_row);
}
}
}