背景
在工作中需要对比数据,然后输出一份world文档的对比报告。这需要用C#来读写word文件。
用到的工具
NPOI
NPOI 地址:NPOI
NPOI版本:2.6.0
个人项目的运行时版本:.NET Core 3.1
解决思路:
既然是要输出一份报告,那么报告的格式是固定的,只需要将报告需要改变的内容进行特殊标记,然后用具体的值替换掉即可
报告部分内容如下:
计算成功successCount,成功率successRate%
这里的successCount 和 successRate 就是要改变的值
接下来的代码如下
public class BuildReport
{
private string savePath;
public BuildReport()
{
if (!Directory.Exists("Report"))
{
Directory.CreateDirectory("Report");
}
savePath = Path.Combine(Directory.GetCurrentDirectory(), "Report");
}
public bool Build(string templatePath, Dictionary<string, string> replaceContent)
{
string buildedPath = $"{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}.docx";
string filePath = Path.Combine(savePath, buildedPath);
if (replaceContent.Keys.Count == 0)
{
return false;
}
if (string.IsNullOrEmpty(templatePath) || string.IsNullOrEmpty(filePath))
{
return false;
}
try
{
//读取Word文件,并在此基础上操作
FileStream template = new FileStream(templatePath, FileMode.Open);
//根据提供的文件,创建一个Word文档对象
XWPFDocument doc = new XWPFDocument(template);
//获取Word文档的所有段落对象
IList<XWPFParagraph> paragraphs = doc.Paragraphs;
//处理替换
HandleContent(replaceContent, paragraphs);
IList<XWPFTable> tables = doc.Tables;
int i = 1;
int rowCurrent = 1;
//获取world文档中的表格
foreach (var item in tables)
{
//表格行
// Console.WriteLine($"**********************第{i}个表************************");
List<XWPFTableRow> rows = item.Rows;
foreach (var row in rows)
{
// Console.WriteLine($"---------------第{rowCurrent}行--------------");
List<XWPFTableCell> xWPFTableCells = row.GetTableCells();//表格单元格
foreach (var cell in xWPFTableCells)
{
//单元格
IList<XWPFParagraph> paragraphs1 = cell.Paragraphs;//单元格中的段落
HandleContent(replaceContent, paragraphs1);
}
rowCurrent++;
}
++i;
}
var newFile = File.Create(filePath);
doc.Write(newFile);
newFile.Close();
template.Close();
doc.Close();
}
catch (Exception ex)
{
throw;
}
return false;
}
/// <summary>
/// 处理要替换的值
/// </summary>
/// <param name="replaceContent">要替换的占位符及其值</param>
/// <param name="paragraphs">文档段落</param>
private void HandleContent(Dictionary<string, string> replaceContent, IList<XWPFParagraph> paragraphs)
{
foreach (var item in paragraphs)
{
foreach (var key in replaceContent.Keys)
{
if (!item.ParagraphText.Contains(key))
{
continue;
}
item.ReplaceText(key, replaceContent[key]);
}
}
}
}
程序调用如下
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("successRate", "100");
dic.Add("successCount", "10000");
BuildReport build = new BuildReport();
build.Build("template.docx", dic);