protected MemoryStream ExportWord()
{
string templetePath = Path.Combine(appOptions.Value.WebRootPath, "word\moban\1.docx");
string newTempletePath = Path.Combine(appOptions.Value.WebRootPath, "word\tempWord");
string newTempleteFileName = Guid.NewGuid().ToString() + ".docx";
if (!Directory.Exists(newTempletePath))
{
Directory.CreateDirectory(newTempletePath);
}
string newTempleteFullPath = Path.Combine(newTempletePath, newTempleteFileName);
System.IO.File.Copy(templetePath, newTempleteFullPath);//拷贝doc模板
//读取Word模板
FileStream fileStream = new FileStream(newTempleteFullPath, FileMode.Open, FileAccess.Read);
XWPFDocument myDoc = new XWPFDocument(fileStream);
//初始化模型
MemberApplyItem role = new MemberApplyItem
{
Num = Model.Num,
Name = Model.Name,
Address = Model.Address,
LawPerson = Model.LawPerson,
LawPhone = Model.LawPhone,
Capital = Model.Capital,
OutVal = Model.OutVal,
LinkMail = Model.LinkMail,
LType = Model.LType,
LVD = Model.LVD,
LID = Model.LID,
AboutUs = Model.Name
};
////遍历段落,替换内容
//foreach (var para in myDoc.Paragraphs)
//{
// ReplaceKey(userInfo, para);
//}
//遍历table,替换单元格内容
foreach (var table in myDoc.Tables)
{
foreach (var row in table.Rows)
{
foreach (var cell in row.GetTableCells())
{
foreach (var para in cell.Paragraphs)
{
ReplaceKey(role, para);
}
}
}
}
MemoryStream ms = new MemoryStream();
myDoc.Write(ms);
return ms;
}
/// <summary>
/// word模板内容替换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="etity">实体数据</param>
/// <param name="para">段落</param>
private static void ReplaceKey<T>(T etity, XWPFParagraph para)
{
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}";//Word模板中设定的需要替换的标签
object value = p.GetValue(etity);
if (value == null)
{
value = "";
}
if (text.Equals(propteryName))
{
text = text.Replace(propteryName, value.ToString());
}
run.SetText(text);//替换标签文本(重要)
}
}
}