翻譯|使用教程|編輯:胡濤|2022-04-24 11:32:53.963|閱讀 172 次
概述:本文重點介紹如何借助 Spire.Doc for .NET 在 C# 中創建 IF 字段。我們一起使用 IF 字段和 MERGEFIELD 字段,,歡迎查閱!
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
通常我們需要根據不同的條件向讀者顯示不同的文本和信息。在這種情況下,我們需要創建 if 字段來決定向讀者顯示哪個結果。本文重點介紹如何借助 Spire.Doc for .NET 在 C# 中創建 IF 字段。我們一起使用 IF 字段和 MERGEFIELD 字段。
{IF { MERGEFIELD Count } > "100" "謝謝" "最低訂購量為 100 件"}
第一步:新建一個word文檔。
Document document = new Document();
第 2 步:為文檔添加一個新部分。
Section section = document.AddSection();
第 3 步:為該部分添加一個新段落。
Paragraph paragraph = section.AddParagraph();
第 4 步:定義創建 IF 字段的方法。
CreateIfField(document, paragraph);
第 5 步:定義合并數據。
string[] fieldName = {"Count"}; string[] fieldValue = { "2" };
第 6 步:將數據合并到 IF 字段中。
document.MailMerge.Execute(fieldName, fieldValue);
第 7 步:更新文檔中的所有字段。
document.IsUpdateFields = true;
第 8 步:將文檔保存到文件中。
document.SaveToFile("sample.docx", FileFormat.Docx);
以下 CreateIfField() 方法顯示了如何創建 IF 字段,如:
{IF { MERGEFIELD Count } > "100" "Thanks" " 最低訂購量為 100 個單位 "}
static void CreateIfField(Document document, Paragraph paragraph) { IfField ifField = new IfField(document); ifField.Type = FieldType.FieldIf; ifField.Code = "IF "; paragraph.Items.Add(ifField); paragraph.AppendField("Count",FieldType.FieldMergeField); paragraph.AppendText(" > "); paragraph.AppendText("\"100\" "); paragraph.AppendText("\"Thanks\" "); paragraph.AppendText("\"The minimum order is 100 units\""); IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; paragraph.Items.Add(end); ifField.End = end as FieldMark; }
檢查有效截圖如下:
完整代碼:
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace CreatIF { class Program { static void Main(string[] args) { Document document = new Document(); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(); CreateIfField(document, paragraph); string[] fieldName = { "Count" }; string[] fieldValue = { "2" }; document.MailMerge.Execute(fieldName, fieldValue); document.IsUpdateFields = true; document.SaveToFile("sample.docx", FileFormat.Docx); } static void CreateIfField(Document document, Paragraph paragraph) { IfField ifField = new IfField(document); ifField.Type = FieldType.FieldIf; ifField.Code = "IF "; paragraph.Items.Add(ifField); paragraph.AppendField("Count", FieldType.FieldMergeField); paragraph.AppendText(" > "); paragraph.AppendText("\"100\" "); paragraph.AppendText("\"Thanks\" "); paragraph.AppendText("\"The minimum order is 100 units\""); IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; paragraph.Items.Add(end); ifField.End = end as FieldMark; } } }
歡迎下載|體驗更多E-iceblue產品
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn