using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelHelper
{
public class WordNpoiHelper : IWordHelper
{
XWPFDocument doc;
string srcPath = @"../Template/temple.docx";
string dstPath = @"../Output/";
public WordNpoiHelper(string fileName)
{
DstPath += fileName;
File.Copy(SrcPath, DstPath, true);
DocInit(DstPath);
}
public void TextReplace(string oldStr, string newStr)
{
IList<XWPFParagraph> paragraphs = doc.Paragraphs;
foreach (XWPFParagraph para in paragraphs)
{
string text = para.ParagraphText;
if (text.Contains(oldStr))
{
para.ReplaceText(oldStr, newStr);
}
}
foreach (XWPFTable table in doc.Tables)
{
foreach (XWPFTableRow row in table.Rows)
{
foreach (XWPFTableCell cell in row.GetTableCells())
{
foreach (XWPFParagraph para in cell.Paragraphs)
{
string text = para.ParagraphText;
if (text.Contains(oldStr))
{
para.ReplaceText(oldStr, newStr);
}
}
}
}
}
}
public string SrcPath
{
get
{
return srcPath;
}
set
{
srcPath = value;
}
}
public string DstPath
{
get
{
return dstPath;
}
set
{
dstPath = value;
}
}
public void Dispose()
{
using (FileStream fileStreamWrite = new FileStream(DstPath, FileMode.Create, FileAccess.Write))
{
doc.Write(fileStreamWrite);
}
}
public void DocInit(string dstPath)
{
using (FileStream fileStream = new FileStream(dstPath, FileMode.Open, FileAccess.Read))
{
doc = new XWPFDocument(fileStream);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelHelper
{
public interface IWordHelper:IOfficeHelper
{
void TextReplace(string oldStr, string newStr);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelHelper
{
public interface IOfficeHelper:IDisposable
{
string SrcPath
{
get;
set;
}
string DstPath
{
get;
set;
}
}
}
调用示例
using ExcelHelper;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelTest
{
internal class Program
{
static void Main(string[] args)
{
string fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}.docx";
using (WordNpoiHelper excelNpoiHelper = new WordNpoiHelper(fileName))
{
excelNpoiHelper.TextReplace("12345","54321");
}
}
}
}