Spire.Docは下図のように様々なフィールド操作を行うことができます。
今回はSpire.Docを使ってFieldDate(日付),FieldIf及びTOC(目次)といったフィールドの作成する方法を紹介します。
下準備
1.E-iceblueの公式サイトからFree Spire.Doc for .NET無料版をダウンロードしてください。
2.Visual Studioを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいDoc.dllを参照に追加してください。(Net 4.0を例としたら、デフォルトパスは“Bin→NET4.0→Spire.Doc.dll”というようです。)
FieldDate
usingSpire.Doc;usingSpire.Doc.Documents;usingSpire.Doc.Fields;namespaceConsoleApplication31{classProgram{staticvoidMain(string[]args){//word objectを作成します。Documentdocument=newDocument();//sectionとparagraphを追加します。Sectionsection=document.AddSection();Paragraphparagraph=section.AddParagraph();//paragraphにテキストを追加します。paragraph.AppendText("今日の日付: ");//日付フィールドを設定します。Fieldfield=paragraph.AppendField("Date",FieldType.FieldData)asField;field.Code=@"DATE \@"+"\"yyyy年MM月dd日 \"";//保存します。document.SaveToFile("Sample.docx",FileFormat.Docx2013);}}}
FieldIf
IFフィールドを使うと、条件に応じて結果を分けることができます。 (IFフィールドの演算子の後はスペース必要)
{IF 条件 真の場合 偽の場合}
usingSpire.Doc;usingSpire.Doc.Documents;usingSpire.Doc.Fields;usingSpire.Doc.Interface;namespaceConsoleApplication31{classProgram{staticvoidMain(string[]args){Documentdocument=newDocument();Sectionsection=document.AddSection();Paragraphparagraph=section.AddParagraph();//CreateFieldメソッドを使用して値を指定します。CreateIfField(document,paragraph);string[]fieldName={"Count"};string[]fieldValue={"100"};//Ifフィールドに値をマージします。document.MailMerge.Execute(fieldName,fieldValue);//フィールドを更新します。document.IsUpdateFields=true;//保存しますdocument.SaveToFile("sample.docx",FileFormat.Docx);}staticvoidCreateIfField(Documentdocument,Paragraphparagraph){ //Ifフィールドを追加して条件を設定します。IfFieldifField=newIfField(document);ifField.Type=FieldType.FieldIf;ifField.Code="IF ";paragraph.Items.Add(ifField);paragraph.AppendField("Count",FieldType.FieldMergeField);paragraph.AppendText(" > ");paragraph.AppendText("\"60\" ");paragraph.AppendText("\"合格\" ");paragraph.AppendText("\"不合格\"");IParagraphBaseend=document.CreateParagraphItem(ParagraphItemType.FieldMark);(endasFieldMark).Type=FieldMarkType.FieldEnd;paragraph.Items.Add(end);ifField.End=endasFieldMark;}}}
TOC
AppendTOC()メソッドで直接にTOCを追加できます。
usingSpire.Doc;usingSpire.Doc.Documents;namespaceConsoleApplication31{classProgram{staticvoidMain(string[]args){Documentdocument=newDocument();Sectionsection=document.AddSection();Paragraphparagraph=section.AddParagraph();//TOCを追加しますparagraph.AppendTOC(1,3);//段落にテキストを追加します。Paragraphpara1=section.AddParagraph();para1.AppendText("Head1");para1.ApplyStyle(BuiltinStyle.Heading1);Paragraphpara2=section.AddParagraph();para2.AppendText("Head2");para2.ApplyStyle(BuiltinStyle.Heading2);//TOCを更新しますdocument.UpdateTableOfContents();//保存しますdocument.SaveToFile("TOC.docx",FileFormat.Docx);}}}