/// <summary> /// 替换word中指定内容 /// </summary> /// <param name="wordPath">路径</param> /// <param name="keyName">被替换内容</param> /// <param name="keyValue">替换内容</param> /// <returns></returns> public string ReplaceValueByKeyName(string wordPath, string keyName, string keyValue) { FileStream fs = new FileStream(wordPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); XWPFDocument docx = new XWPFDocument(fs);//打开07(.docx)以上的版本的文档 //遍历word中的段落 foreach (var para in docx.Paragraphs) { if (!para.ParagraphText.Contains(keyName)) continue; para.ReplaceText(para.ParagraphText, keyValue);
// NewLine(para, "测试换行"); } FileStream output = new FileStream(wordPath, FileMode.Create); docx.Write(output); fs.Close(); fs.Dispose(); output.Close(); output.Dispose(); return wordPath; }
/// <summary> /// 替换指定内容为图片|图片居中 /// </summary> /// <param name="wordPath">文件路径</param> /// <param name="keyName">需被替换内容</param> /// <param name="imgPath">图片路径</param> /// <param name="imgType">图片类型</param> public void InsertImgToKey(string wordPath, string keyName, string imgPath, PictureType imgType = PictureType.JPEG) { FileStream fs = new FileStream(wordPath, FileMode.Open, FileAccess.Read); XWPFDocument myDocx = new XWPFDocument(fs);//打开07(.docx)以上的版本的文档 //遍历word中的段落 foreach (var para in myDocx.Paragraphs) { if (!para.ParagraphText.Contains(keyName)) continue; para.ReplaceText(para.ParagraphText, string.Empty); XWPFRun run = para.CreateRun(); using (FileStream picData = new FileStream(imgPath, FileMode.Open, FileAccess.Read)) { run.AddPicture(picData, (int)imgType, imgPath, 100 * 9525, 100 * 9525); } para.Alignment = ParagraphAlignment.CENTER; break; } //遍历表格 foreach (var table in myDocx.Tables) { foreach (var row in table.Rows) { foreach (var cell in row.GetTableCells()) { foreach (var para in cell.Paragraphs) { if (!para.ParagraphText.Contains(keyName)) continue; para.ReplaceText(para.ParagraphText, string.Empty); XWPFRun run = para.CreateRun(); using (FileStream picData = new FileStream(imgPath, FileMode.Open, FileAccess.Read)) { run.AddPicture(picData, (int)imgType, imgPath, 100 * 9525, 100 * 9525); } para.Alignment = ParagraphAlignment.CENTER; break; } } } } FileStream output = new FileStream(wordPath, FileMode.Create); myDocx.Write(output); fs.Close(); fs.Dispose(); output.Close(); output.Dispose(); }
换行
private void NewLine(XWPFParagraph paragraph) { paragraph.CreateRun().AddCarriageReturn();//新增式换行--当前行之后 paragraph.CreateRun().SetText(""); //para.InsertNewRun(row).AddCarriageReturn(); //插入式换行--当前行之前 //para.InsertNewRun(row).SetText("换行001"); }
注:换行问题,不同版本的word或者npoi 版本操作方式存在不一致现象,需要亲测
private void NewLine(XWPFParagraph paragraph, string value) { value = value + " "; //paragraph.CreateRun().AddCarriageReturn();//新增式换行--当前行之后 paragraph.CreateRun().SetText(value); //paragraph.CreateRun().AddCarriageReturn(); //paragraph.CreateRun().Paragraph.CreateRun().AddCarriageReturn(); //paragraph.CreateRun().Paragraph.CreateRun().SetText(value); }