using NPOI.XWPF.UserModel;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Helper
{
public class WordHelper
{
/// <summary>
/// model 可以为DataTable 或者 匿名类
/// </summary>
/// <param name="filePath"></param>
/// <param name="outPath"></param>
/// <param name="model"></param>
public Stream Export(string filePath,object model)
{
using (FileStream stream = File.OpenRead(filePath))
{
var wordStream = new MemoryStream();
XWPFDocument doc = new XWPFDocument(stream);
//遍历段落
foreach (var para in doc.Paragraphs)
{
if (model is DataTable)
{
ReplaceKeyByDataTable(para, (DataTable)model);
}
else
{
ReplaceKey(para, model);
}
}
//遍历表格
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)
{
if (model is DataTable)
{
ReplaceKeyByDataTable(para,(DataTable) model);
}
else
{
ReplaceKey(para, model);
}
}
}
}
}
// FileStream out1 = new FileStream(outPath, FileMode.Create);
doc.Write(wordStream);
return wordStream;
//out1.Close();
}
}
public void ReplaceKey(XWPFParagraph para, object model)
{
string text = para.ParagraphText;
var runs = para.Runs;
string styleid = para.Style;
text = String.Join("", runs.Select(x => x.Text));
Type t = model.GetType();
PropertyInfo[] pi = t.GetProperties();
foreach (PropertyInfo p in pi)
{
if (text.Contains("{$" + p.Name + "}"))
{
text = text.Replace("{$" + p.Name + "}", p.GetValue(model, null).ToString());
}
}
int length = runs.Count();
for (int j = (length - 1); j >= 0; j--)
{
para.RemoveRun(j);
}
//直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
//所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
para.InsertNewRun(0).SetText(text, 0);
}
public void ReplaceKeyByDataTable(XWPFParagraph para, DataTable model)
{
string text = para.ParagraphText;
var runs = para.Runs;
string styleid = para.Style;
text = String.Join("", runs.Select(x => x.Text));
foreach (DataRow p in model.Rows)
{
if (CheckIsMatchTemplateValue(text))
{
var columnName = GetValueFromTemplateVar(text, @"{\$", "}");
if (model.Columns.Contains(columnName))
{
text = text.Replace("{$" + columnName + "}", p[columnName].ToString());
}
}
}
int length = runs.Count();
for (int j = (length - 1); j >= 0; j--)
{
para.RemoveRun(j);
}
//直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
//所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
para.InsertNewRun(0).SetText(text, 0);
}
private bool CheckIsMatchTemplateValue(string value)
{
Regex regex = new Regex(@"([{\$][\w\W]*})");
Match match = regex.Match(value);
return match.Success;
}
private string GetValueFromTemplateVar(string str, string s, string e)
{
Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(str).Value;
}
}
}
WordHelper 类
最新推荐文章于 2023-12-04 09:00:00 发布