NPOI实现word模板替换1

 

 

 

 

 

 

using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace WordExportDemo
{
/// <summary>
/// npoi导出word
/// </summary>
public class DocHelper
{

/// <summary>
///
/// </summary>
/// <param name="model">实体数据</param>
/// <param name="filepath">模板路径</param>
/// <returns></returns>
public static MemoryStream ExportDoc<T>(T model,string filepath)
{
using (FileStream stream = File.OpenRead(filepath))
{
XWPFDocument doc = new XWPFDocument(stream);
//遍历段落
foreach (var para in doc.Paragraphs)
{
ReplaceKey(model,para);
}
//遍历表格
var tables = doc.Tables;
foreach (var table in tables)
{
foreach (var row in table.Rows)
{
foreach (var cell in row.GetTableCells())
{
foreach (var para in cell.Paragraphs)
{
ReplaceKey(model,para);
}
}
}
}
using (MemoryStream ms = new MemoryStream())
{
doc.Write(ms);
return ms;
}
}

}
private static void ReplaceKey<T>(T entity,XWPFParagraph para)
{

try
{
Type entityType = typeof(T);
PropertyInfo[] properties = entityType.GetProperties();
string entityName = entityType.Name;
string paratext = para.ParagraphText;
var runs = para.Runs;
string styleid = para.Style;
string text = "";
foreach (var run in runs)
{
text = run.ToString();
foreach (var p in properties)
{
string propteryName = "$" + p.Name + "$";
object value = p.GetValue(entity);
if (value == null)
{
value = "";
}
if (text.Contains(propteryName))
{
text = text.Replace(propteryName, value.ToString());
}
run.SetText(text);
}

}
}
catch (Exception ex)
{

string msg = ex.Message + ex.StackTrace;
}

}
}
}

posted @ 2021-09-17 21:25  .net&new  阅读(991)  评论(0编辑  收藏  举报