在工作中需要對比資料,然後輸出一份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);