Nuget安装依赖库 NPOI (版本2.6.2)
效果图


核心代码
/// <summary>
/// 修改字符串
/// </summary>
/// <param name="doc"></param>
/// <param name="data">key:占位符,value:替换占位符的字符吕</param>
public void UpStr(XWPFDocument doc, Dictionary<string, string> data)
{
if (doc == null || data == null || data.Count < 1)
{
return;
}
foreach (XWPFTable table in doc.Tables)//遍历所有表格数据
{
foreach (XWPFTableRow row in table.Rows)
{
foreach (XWPFTableCell cell in row.GetTableICells())
{
foreach (var para in cell.Paragraphs)
{
string oldText = para.ParagraphText;
foreach (KeyValuePair<string, string> kv in data)
{
if (oldText.Contains(kv.Key))
{
para.ReplaceText(kv.Key, kv.Value);
}
}
}
}
}
}
foreach (var para in doc.Paragraphs)//遍历所有表格以外的数据
{
string oldText = para.ParagraphText;
foreach (KeyValuePair<string, string> kv in data)
{
if (oldText.Contains(kv.Key))
{
para.ReplaceText(kv.Key, kv.Value);
}
}
}
}
/// <summary>
/// 在指定位置 插入图片
/// </summary>
/// <param name="doc"></param>
/// <param name="data">key:占位符,value:替换占位符的字符串</param>
/// <param name="fs">图片的文件流</param>
/// <param name="placeholder">图片的占位符</param>
/// <param name="width">图片显示的宽度</param>
/// <param name="height">图片显示的高度</param>
public void UpImage(XWPFDocument doc, FileStream fs, string placeholder, int width, int height)
{
if (doc == null || fs == null || fs.Length < 1)
{
return;
}
foreach (XWPFTable table in doc.Tables)//遍历所有表格数据
{
foreach (XWPFTableRow row in table.Rows)
{
foreach (XWPFTableCell cell in row.GetTableICells())
{
foreach (var para in cell.Paragraphs)
{
if (para.ParagraphText.Contains(placeholder))
{
para.Runs[0].AddPicture(fs, 5, "imageName", width, height);
para.ReplaceText(placeholder, "");
}
}
}
}
}
foreach (var para in doc.Paragraphs)//遍历所有表格以外的数据
{
if (para.ParagraphText.Contains(placeholder))
{
para.Runs[0].AddPicture(fs, 5, "imageName", width, height);
para.ReplaceText(placeholder, "");
}
}
fs.Dispose();
}方法调用
// 获取图片
string imagePath = @"F:\image.png";
// 读取图片
FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
var template = @"F:\model.docx";
var outPath = @"F:\outPath.docx";
using (FileStream stream = new FileStream(template, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
XWPFDocument doc = new XWPFDocument(stream);
Dictionary<string, string> data = new Dictionary<string, string>
{
{"$[lqwvje]$","罗分明" }
};
UpStr(doc, data);
UpImage(doc, fs, "$[image]$", 160 * 9525, 100 * 9525);
using (FileStream stream2 = new FileStream(outPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
doc.Write(stream2);
}
doc.Dispose();
}本文来自 www.luofenming.com