Spire.Agent.Office (22)
Reconciliation is one of the most frequent and tedious tasks in corporate finance, and the source data often comes in different forms: bank statements are CSV files exported from online banking, while system transaction records may be PDF detail reports. The two tables have different column names, inconsistent date and amount formats, and even stray spaces and missing values. This article shows how to use Spire.Agent.Office Excel AI capabilities to automatically read CSV and PDF data sources, identify and map column names, clean the data, and finally generate an Excel reconciliation detail report.
For product installation and SpireToken configuration, please refer to Integrate Spire.Agent.Office in a .NET Project. The following examples assume Spire.Agent.Office is installed and SpireToken is configured.
Reconcile by Statement Number
Reconcile and analyze the CSV-format bank statement with the PDF-format system transaction records by statement number.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// Data source files: bank statement (CSV) and system transaction records (PDF)
string[] attachmentPaths = new string[]
{
@"bank-statement.csv",
@"system-records.pdf"
};
// Excel processing configuration
string inputPath = "";
string savePath = "out.xlsx";
// SpireToken Key
string key = "**************************";
string instruction =
"Reconcile the bank statement (CSV) with the system transaction records (PDF) in the attachments: " +
"1. Establish the column mapping of the two tables by semantics: transaction date, amount, counterparty account, description, statement number; " +
"2. Cleaning: strip leading/trailing and internal extra spaces from text; write dates as yyyy-MM-dd text; convert amounts to numbers by removing currency symbols and thousands separators; mark empty description or empty counterparty as 'Unknown', mark empty amount as 'Amount missing'; " +
"3. Match row by row using the statement number as the unique key, and mark the status: 'Matched'/'Amount mismatch'/'Bank only'/'System only'; " +
"4. Generate a 'Reconciliation Detail' worksheet: each record with bank amount, system amount, difference, status and remark; " +
"5. Highlight difference rows: yellow for amount mismatch, orange for bank only, blue for system only; " +
"Finally save the output as an Excel file";
// Call the Excel document processing function
AIResult result = ExecuteDemoExcel(instruction, inputPath, savePath, key, attachmentPaths);
// Execute Excel document AI processing
static AIResult ExecuteDemoExcel(string instruction, string inputPath, string savePath, string key, string[] attachmentPaths)
{
// Create an AIOptions configuration object
AIOptions options = new AIOptions();
options.SpireToken = key;
// Use the Workbook object to process the Excel document
using (Workbook workbook = new Workbook())
{
// Load the Excel template from a file
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
workbook.LoadFromFile(inputPath);
}
// Create the AI document processor
AIWorkbookProcessor processor = workbook.AI(options);
// Execute the AI instruction
return processor.ExecuteInstruction(workbook, instruction, savePath, attachmentPaths);
}
}
Original bank statement CSV
Original system transaction PDF
Reconciliation detail after Excel AI reconciliation 
Reconcile by Date and Amount Combination
When the data source does not contain a unique statement number, you can use the "transaction date + amount" combination as the matching key for reconciliation: first group by date, then pair the records by amount within the same date.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// Data source files without statement numbers: bank statement (CSV) and system transaction records (PDF)
string[] attachmentPaths = new string[]
{
@"bank-statement-noId.csv",
@"system-records-noId.pdf"
};
// Excel processing configuration
string inputPath = "";
string savePath = "out.xlsx";
// SpireToken Key
string key = "**************************";
string instruction =
"Reconcile the bank statement (CSV) with the system transaction records (PDF) in the attachments: " +
"1. Establish the column mapping of the two tables by semantics: transaction date, amount, counterparty account, description; " +
"2. Cleaning: strip extra spaces from text; write dates as yyyy-MM-dd text; convert amounts to numbers; mark missing values as 'Unknown' or 'Amount missing'; " +
"3. Use the 'transaction date + amount' combination as the matching key: first group by date, then pair the records by amount within the same date, and mark the status: 'Matched'/'Amount mismatch'/'Bank only'/'System only'; " +
"4. Generate a 'Reconciliation Detail' worksheet (bank amount, system amount, difference, status); " +
"5. Highlight difference rows: yellow for amount mismatch, orange for bank only, blue for system only; " +
"Finally save the output as an Excel file";
// Call the Excel document processing function
AIResult result = ExecuteDemoExcel(instruction, inputPath, savePath, key, attachmentPaths);
// Execute Excel document AI processing
static AIResult ExecuteDemoExcel(string instruction, string inputPath, string savePath, string key, string[] attachmentPaths)
{
// Create an AIOptions configuration object
AIOptions options = new AIOptions();
options.SpireToken = key;
// Use the Workbook object to process the Excel document
using (Workbook workbook = new Workbook())
{
// Load the Excel template from a file
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
workbook.LoadFromFile(inputPath);
}
// Create the AI document processor
AIWorkbookProcessor processor = workbook.AI(options);
// Execute the AI instruction
return processor.ExecuteInstruction(workbook, instruction, savePath, attachmentPaths);
}
}
Original bank statement CSV
Original system transaction PDF
Reconciliation detail after Excel AI reconciliation 
Comparison with Traditional SDK API Processing
| Traditional Spire.Office for .NET API | Spire.Agent.Office Processing | |
|---|---|---|
| Driving approach | Requires writing large amounts of code for CSV/PDF parsing, column mapping, data cleaning, matching and exception logic | Describe reconciliation rules in natural language, and AI understands and orchestrates the execution automatically |
| Data format | CSV and PDF must be parsed with different components, each with its own format | Directly attach CSV and PDF, and AI understands the content automatically |
| Field mapping | Hard-coded column name mappings; changing column names or formats requires code changes | AI maps columns automatically based on column names and content semantics |
| Exception handling | Need to hand-write difference judgment, alert text and style logic | AI automatically identifies differences and provides handling suggestions |
Frequently Asked Questions
Inconsistent date and amount formats in the bank statement CSV
Cause: In the CSV exported from online banking, dates may be written as 2026-07-01, 2026/7/1, etc., and amounts may carry ¥, thousands separators, or leading/trailing spaces, leading to misjudgment during matching.
Solution: Explicitly require in the instruction "unify dates as yyyy-MM-dd and amounts as numeric formats and remove spaces", and AI will complete the standardization automatically before reconciliation.
The system transaction PDF table spans pages or has headers/footers
Cause: PDF detail reports may have pagination, repeated headers, or footer annotations, which affect AI's reading of the table data.
Solution: Add "ignore headers/footers and repeated header rows, only read the table data rows" to the instruction.
The same amount appears multiple times on the same day, causing mismatches
Cause: When reconciling by the "date + amount" combination, there may be multiple transactions with the same amount on the same day, making the exact correspondence impossible to determine.
Solution: Prefer precise reconciliation by statement number; if there is really no statement number, you can require in the instruction to "mark records that cannot be matched one-to-one on the same day as 'Amount mismatch'".
Get a SpireToken Key
- Contact [email protected] or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key
Configure it in code:
AIOptions options = new AIOptions();
options.SpireToken = key;
Automatically Comparing Multi-format Quotation Sheets with Spire.Agent.Office
2026-08-13 02:42:10 Written by Lisa LiIn procurement and sales scenarios, price comparison is one of the most critical and time-consuming steps. Procurement teams receive quotation sheets from various vendors — some organized by rows, some by columns, some containing multiple hidden costs, and some with inconsistent units. The Spire.Agent.Office Excel AI agent can understand quotation sheets in different formats, automatically align each vendor's quotations to a unified template, calculate line-item totals and grand totals, and mark the lowest prices.
This article explains how to use the Spire.Agent.Office Excel AI capability to automatically align quotation sheets from multiple different vendors to a unified template, calculate totals for comparison, and highlight the lowest price.
For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The following examples assume that Spire.Agent.Office is installed and SpireToken is configured.
Excel Format Quote Comparison
The core challenge of comparing multi-format quotation sheets is that each vendor's quotation sheet differs.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// Quotation files from different vendors
string[] attachmentPaths = new string[]
{
@"vendor_A.xlsx",
@"vendor_B.xlsx",
@"vendor_C.xlsx",
@"vendor_D.xlsx"
};
// Output template file
string inputPath = @"template.xlsx";
// Result document
string savePath = @"quote-comparison.xlsx";
string key = "**************************";
string instruction =
"Read the quotation sheets of the vendors in the attachments (Vendor A, Vendor B, Vendor C, Vendor D) and process them as follows:" +
"1. Identify the item, unit price, quantity, and total price columns in each quotation sheet, and align them to the Unit Price and Amount columns of the corresponding vendor (A, B, C, D) in the template;" +
"2. If a vendor has not quoted a product, leave the corresponding unit price and amount cells blank and mark them as 'Not quoted';" +
"3. Calculate the amount (quantity x unit price) for each product of each quoting vendor and fill it into the corresponding columns; compute each vendor's total quotation at the bottom of the template;" +
"4. In the total price row, fill the cell of the vendor with the lowest total quotation with a green background (RGB:198,224,180);" +
"5. In the 'Lowest Price Vendor' column, mark the vendor that offers the lowest unit price for each product, and fill the corresponding lowest unit price into the 'Lowest Price' column;" +
"6. Preserve the template's layout style, fonts, and column widths;" +
"Finally save the output as an Excel file";
// Call the Excel document processing function
AIResult result = ExecuteDemoExcel(instruction, inputPath, savePath, key, attachmentPaths);
// Execute Excel document AI processing
static AIResult ExecuteDemoExcel(string instruction, string inputPath, string savePath, string key, string[] attachmentPaths)
{
// Create the AIOptions configuration object
AIOptions options = new AIOptions();
options.SpireToken = key;
// Use the Workbook object to process the Excel document
using (Workbook workbook = new Workbook())
{
// Load the Excel template from file
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
workbook.LoadFromFile(inputPath);
}
// Create the AI document processor
AIWorkbookProcessor processor = workbook.AI(options);
// Execute the AI instruction
return processor.ExecuteInstruction(workbook, instruction, savePath, attachmentPaths);
}
}
Original quotation sheets of each vendor
Original Excel template
Comparison summary generated by Excel AI 
PDF Format Quote Comparison
When the original quotations are in PDF format, Spire.Agent.Office can equally extract the required data with ease and automatically complete the summary statistics. Simply add the source documents in different formats, and the AI instruction can be reused without reconfiguration, greatly improving processing efficiency.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// Quotation files from different vendors
string[] attachmentPaths = new string[]
{
@"vendor_A.pdf",
@"vendor_B.pdf",
@"vendor_C.pdf",
@"vendor_D.pdf"
};
// Output template file
string inputPath = @"template.xlsx";
// Result document
string savePath = @"quote-comparison.xlsx";
string key = "**************************";
string instruction =
"Read the quotation sheets of the vendors in the attachments (Vendor A, Vendor B, Vendor C, Vendor D) and process them as follows:" +
"1. Identify the item, unit price, quantity, and total price columns in each quotation sheet, and align them to the Unit Price and Amount columns of the corresponding vendor (A, B, C, D) in the template;" +
"2. If a vendor has not quoted a product, leave the corresponding unit price and amount cells blank and mark them as 'Not quoted';" +
"3. Calculate the amount (quantity x unit price) for each product of each quoting vendor and fill it into the corresponding columns; compute each vendor's total quotation at the bottom of the template;" +
"4. In the total price row, fill the cell of the vendor with the lowest total quotation with a green background (RGB:198,224,180);" +
"5. In the 'Lowest Price Vendor' column, mark the vendor that offers the lowest unit price for each product, and fill the corresponding lowest unit price into the 'Lowest Price' column;" +
"6. Preserve the template's layout style, fonts, and column widths;" +
"Finally save the output as an Excel file";
// Call the Excel document processing function
AIResult result = ExecuteDemoExcel(instruction, inputPath, savePath, key, attachmentPaths);
// Execute Excel document AI processing
static AIResult ExecuteDemoExcel(string instruction, string inputPath, string savePath, string key, string[] attachmentPaths)
{
// Create the AIOptions configuration object
AIOptions options = new AIOptions();
options.SpireToken = key;
// Use the Workbook object to process the Excel document
using (Workbook workbook = new Workbook())
{
// Load the Excel template from file
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
workbook.LoadFromFile(inputPath);
}
// Create the AI document processor
AIWorkbookProcessor processor = workbook.AI(options);
// Execute the AI instruction
return processor.ExecuteInstruction(workbook, instruction, savePath, attachmentPaths);
}
}
Original PDF quotation of each vendor
Original Excel template
Comparison summary generated by Excel AI 
Comparison with Traditional SDK API Processing
| Spire.Office for .NET API | Spire.Agent.Office | |
|---|---|---|
| Code Volume | Reading data, mapping rows and columns, filling formulas, and applying conditional formatting require extensive code | Handled intelligently with a single natural language instruction |
| Format Adaptation | With the traditional SDK APIs, quotation sheets in different formats must be processed with different products | Just use the Excel AI to process data sources in various formats |
| Calculation Logic | Formulas and formatting must be set through APIs | AI understands and automatically completes the calculation and formatting |
| Requirement Changes | Modify the code and re-debug | Modify the instruction, effective immediately |
FAQ
Merged Cells in Quotation Sheets Cause Data Misalignment
Cause: Vendor quotation sheets may contain merged title cells or category labels merged across rows, which affect the AI's judgment of the row/column structure.
Solution: Clearly specify in the instruction "ignore the merged header rows and start reading data from row X," or provide a template file as a structural reference. If the issue persists, add the description "treat merged cells as ordinary cells and take their top-left value."
Processed Format Does Not Match Expectations
Cause: When understanding complex table layouts, the AI model may not preserve details such as column widths, row heights, and fonts precisely enough.
Solution: Add specific descriptions to the instruction, such as "preserve the existing column widths, row heights, fonts, borders, and alignment of the template."
Some Products Lack Vendor Quotations
Cause: The product lists provided by different vendors are not completely consistent, and some vendors may not have quoted certain products.
Solution: Clearly specify how to handle missing items in the instruction, such as "mark the cells without quotations as 'Not quoted' or leave them blank," and the AI will automatically identify and process them as required.
Obtaining a SpireToken Key
- Contact [email protected] or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key.
Configure it in code:
AIOptions options = new AIOptions();
options.SpireToken = key;
AI Contract Review in C#: Automate Contract Processing in .NET
2026-08-12 06:46:25 Written by Allen Yang
AI contract automation in C# means combining AI language understanding with document-processing capabilities inside your .NET application, so developers can review, extract, and generate contract documents by describing the task in natural language instead of writing field-mapping and layout code for every template. In practice, this is document automation in .NET where a natural-language instruction replaces the field-mapping code. Spire.Agent.Office is a document AI agent SDK that handles the language; a deterministic document layer guarantees real, well-formed Word and PDF files.
Quick Navigation
- Why Contract Review Is a Good Fit for AI
- What an AI Contract Agent Can and Cannot Do
- Common Contract Automation Scenarios
- Three Ways to Automate Contract Processing in .NET
- A Working Example: Contract Review and Generation in C#
- Why Use Spire.Agent.Office for AI Contract Automation
- FAQ
1. Why Contract Review Is a Good Fit for AI
Contract work in a developer's world is three repetitive jobs: reading (extracting parties, dates, payment terms, and obligations from agreements that arrive as PDFs and Word files), checking (spotting missing clauses or unusual language), and producing (turning a list of employees or vendors into signed-ready contracts).
For .NET developers, the challenge is not only understanding contract content; it is turning unstructured documents into structured, repeatable workflows your application can own.
Three properties make these tasks ideal for a language model rather than hand-written rules:
- The input is unstructured. Incoming contracts arrive in whatever format the other side sends. Rules that handle one layout break on the next; an LLM reads text directly.
- The output is document-shaped. The deliverable is a real
.docxor.pdfwith correct formatting, not a text blob. This is where a document layer earns its keep. - The volume changes constantly. Onboarding 50 employees or reviewing 200 vendor agreements in a month means a config-driven solution, not re-coding per template.
In practice, review and generation go together: teams want existing contracts summarized and red-flagged, and new contracts generated from a template plus structured data.
2. What an AI Contract Agent Can and Cannot Do
| Can do | Cannot do |
|---|---|
| Extract parties, effective dates, payment terms, obligations | Replace professional legal review for high-risk agreements |
| Summarize long agreements into a one-page brief | Guarantee compliance with local laws |
| Generate contracts in batches from a template + data source | Negotiate or accept terms on your behalf |
| Keep formatting, table styles, and fonts intact | Guarantee output is error-free without review |
| Run inside your own application (no cloud upload) | Interpret new or ambiguous regulations; route to counsel |
| Flag clauses that look unusual for a standard agreement | Reveal hidden risks in intentionally vague clauses |
The division of labor: the agent automates the reading, extraction, and drafting (the hours a paralegal would spend), while a human lawyer owns the final judgment. That boundary is what keeps the tool useful and the process defensible.
3. Common Contract Automation Scenarios
Contract automation spans more than hiring. The same pattern (an instruction, a template, and optional data) covers the scenarios teams search for most:
| Scenario | Example instruction |
|---|---|
| Vendor agreement review | "Review this vendor agreement and flag payment terms, liability caps, and termination conditions that differ from our standard terms." |
| Employment contract generation | "Generate one employment contract per row in 'employees.xlsx' using the template, preserving layout and styling." |
| NDA processing | "Summarize this NDA: confidentiality period, permitted disclosures, and remedies on breach." |
| Lease agreement analysis | "Extract rent, term, renewal options, and maintenance obligations from this lease, and list any unusual clauses." |
Each scenario is the same architecture: an instruction in, a real document out.
4. Three Ways to Automate Contract Processing in .NET
| Approach | Code volume | Format fidelity | Maintenance | Best for |
|---|---|---|---|---|
| Document AI agent (LLM + document layer) | One instruction + ~10 lines | High (real Word/PDF files) | Low (change behavior by editing instructions) | Teams automating contracts without building an LLM pipeline |
| Raw LLM API (OpenAI/Claude + your own code) | High (prompts, parsing, file I/O) | Low (LLMs don't natively read/write Office files) | High (you own RAG, routing, errors) | Teams that already run an LLM stack |
| Traditional SDK (Spire.Office or similar) | Dozens of lines per document type | High (deterministic) | High (every mapping is code) | Fixed, well-specified documents that rarely change |
The key point: an LLM cannot edit a contract template without a document-processing layer, and a traditional SDK cannot understand a natural-language request. A document AI agent combines both.
That is not to say the traditional route is wrong. For fixed, well-specified documents that rarely change, a deterministic SDK is often the right call, and Spire.Office still serves that need. The agent earns its place when templates, inputs, and requirements change often enough that re-coding becomes the bottleneck.
Why a Raw LLM API Is Not Enough for Contracts
Calling gpt-4 or claude directly to "generate a contract" fails in three ways that matter in production:
- It cannot reliably read or write Office files. LLMs see text, not
.docxand.pdfstructure. Reading a Word template, keeping a table intact, or producing a valid PDF usually requires a separate extraction and reconstruction pipeline you have to build yourself. - Formatting is not guaranteed. Contract templates carry clause numbering, tables, and fonts that matter to the recipient. A raw LLM returns text, and the formatting you lose is exactly what legal and HR departments care about.
- You reimplement the whole orchestration. Prompt design, field mapping, error handling, file I/O, and output validation become your code to own and maintain.
A document AI agent pairs the model's language understanding with deterministic document APIs: the model decides what to extract or fill, and the document layer guarantees the file is real and well-formed. That is the difference between a demo and a workflow a team can ship.
5. A Working Example: Contract Review and Generation in C#
Below is a task the legal and procurement teams repeat every week: reviewing newly arrived supplier agreements, then issuing contracts for the vendors that get approved. The implementation uses Spire.Agent.Office for .NET, an AI agent that processes Word, Excel, PowerPoint, and PDF documents through natural-language instructions. The example is designed around that workflow rather than copied from a tutorial; the official Getting Started and Batch Contract Generation tutorials document the API setup step by step, while this section focuses on the C# integration patterns.

1. Review every agreement that arrived this week. Configure the agent once, then read the inbox folder and have each agreement summarized as a Markdown brief you can paste into a review tracker:
using System.IO;
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;
using Spire.Pdf;
AIOptions agentOptions = new AIOptions();
agentOptions.WorkDir = @"C:\legal-ops\output";
agentOptions.SpireToken = spireToken;
string reviewPrompt =
"Review this supplier agreement and write a Markdown brief: a one-row table with " +
"the parties, effective date, payment terms, and termination clause, then a bullet " +
"list of any clauses that look unusual for a standard supplier agreement. " +
"Save the brief to the specified output path as Markdown.";
Directory.CreateDirectory(@"C:\legal-ops\output");
foreach (string file in Directory.GetFiles(@"C:\legal-ops\inbox", "*.pdf"))
{
string briefPath = Path.Combine(
@"C:\legal-ops\output", Path.GetFileNameWithoutExtension(file) + ".md");
using (PdfDocument agreement = new PdfDocument())
{
agreement.LoadFromFile(file);
AIResult result = agreement.AI(agentOptions).ExecuteInstruction(
agreement, reviewPrompt, briefPath, new string[] { });
if (result == null || !result.Success)
{
throw new InvalidOperationException(
$"Review failed for {Path.GetFileName(file)}: {result?.ErrorMessage}");
}
}
}
Key API Calls
PdfDocument.LoadFromFile()-- opens the supplier agreement PDFagreement.AI(agentOptions)-- attaches the AI document processorExecuteInstruction(doc, instruction, savePath, attachments)-- runs the review and writes the Markdown briefAIResult.Success/AIResult.ErrorMessage-- verifies the result and surfaces errors
Output

2. Issue contracts for the vendors you approved. One template plus the approval list. The template holds {{Placeholder}} markers for the vendor data; pass null as the output path so the agent writes one independent PDF per vendor into the working directory:
string[] attachments = { @"C:\legal-ops\data\approved-vendors.xlsx" };
using (Document contract = new Document())
{
contract.LoadFromFile(@"C:\legal-ops\templates\supplier-contract.docx");
AIResult result = contract.AI(agentOptions).ExecuteInstruction(
contract,
"Issue one purchase contract per approved vendor: read 'approved-vendors.xlsx' " +
"row by row, fill the {{Placeholder}} fields in this template with each vendor's " +
"data, preserve the template layout and styling, and save each contract as an " +
"independent PDF in the work directory.",
null, // null output path -> the agent writes each contract into WorkDir
attachments);
if (result == null || !result.Success)
{
throw new InvalidOperationException(
$"Contract issuing failed: {result?.ErrorMessage}");
}
}
Key API Calls
Document.LoadFromFile()-- loads the contract templatecontract.AI(agentOptions)-- attaches the AI document processorExecuteInstruction(doc, instruction, savePath, attachments)-- issues one independent contract per vendor rowAIResult.Success/AIResult.ErrorMessage-- verifies the result and surfaces errors
Output
Each contract is written to a session subfolder the agent manages under WorkDir (e.g. output\.office_use_tmp\Word\<session>\output_contracts), so point WorkDir at your archive folder and collect the issued contracts from there.

One template, one spreadsheet, and the same instruction drives every contract, each issued with its formatting intact. Output can be saved as PDF, DOCX, DOC, HTML, Markdown, or XPS to fit your archiving workflow. You can also build more complex templates than simple field filling -- the official Generate Various Word Templates tutorial covers placeholders, conditional sections, and other template patterns the agent can fill.
Why This Is Different: Traditional SDK vs. AI Agent
The value of the agent is clearest side by side. With the traditional SDK you locate each {{Placeholder}} and replace it by hand, one line per field, map every spreadsheet column to its placeholder, then loop the rows and export one file per row. That is dozens of lines you maintain every time the template or the data layout changes. The sketch below (simplified for illustration) shows the shape of that work:
// Traditional SDK (illustrative): every {{Placeholder}} is located and
// replaced by hand -- one line per field
Document doc = new Document();
doc.LoadFromFile(@"C:\legal-ops\templates\supplier-contract.docx");
doc.Replace("{{SupplierName}}", vendor.SupplierName, false, true);
doc.Replace("{{Amount}}", vendor.Amount.ToString(), false, true);
doc.Replace("{{PaymentTerms}}", vendor.PaymentTerms, false, true);
doc.Replace("{{EffectiveDate}}", vendor.EffectiveDate.ToString("yyyy-MM-dd"), false, true);
doc.SaveToFile(@"C:\legal-ops\output\PO-001.pdf"); // ...repeat for each vendor row
The AI agent replaces that orchestration with one instruction:
contract.AI(agentOptions).ExecuteInstruction(
contract,
"Issue one purchase contract per approved vendor: read 'approved-vendors.xlsx' " +
"row by row, fill the {{Placeholder}} fields in this template with each vendor's " +
"data, preserve the template layout and styling, and save each contract as an " +
"independent PDF in the work directory.",
null,
attachments);
Both produce the same contracts. Where the SDK grows a Replace call for every placeholder and a mapping for every column, the agent absorbs the same work into one instruction. When the template or the data layout changes, you edit the instruction, not the code.

6. Why Use Spire.Agent.Office for AI Contract Automation
The three-way comparison above is deliberately product-neutral; the same pattern works with any capable LLM. Where Spire.Agent.Office earns its place for .NET teams is in three specific areas:
- Native Office document processing. Word, Excel, PowerPoint, and PDF are first-class citizens, not formats you bolt on. The agent reads and writes real files across all four.
- Formatting is preserved. Enterprise contracts carry clause numbering, tables, and fonts that must survive processing. The agent's document layer keeps them intact. Include "preserve the original document layout and styling" in your instruction and the output stays true to the template.
- Native .NET integration. It is a C# SDK that drops into an existing .NET application. No separate document-processing service to build or maintain, no cross-service plumbing. The example above is the whole integration surface.
If you already run Spire.Office for document processing, the agent is the natural next layer: the same Document object gains an AI() processor that turns instructions into executed workflows.
7. FAQ
Can AI contract review work with text-based PDFs?
Yes. The review example above loads a supplier-agreement.pdf directly, and the agent reads and analyzes the document in its native format. Support covers standard and encrypted text-based PDFs. Image-only scans have no extractable text layer, so convert them to searchable text first (for example with OCR) before running the review.
Can contract data stay inside my environment?
Yes, with one important nuance. Spire.Agent.Office runs from your own application, so the SDK, templates, and document processing stay inside your environment. Contract files are not uploaded to a third-party document service for storage or conversion. To analyze contract content, the AI needs the relevant text, and it is sent to the model for processing; that is an inherent step of any AI workflow. If you deploy your own model on your local network, the content stays entirely within your infrastructure. If you connect through a hosted model API such as OpenAI or Azure OpenAI, the relevant content is transmitted to that provider over the network per your configuration.
Can I use my own AI model with Spire.Agent.Office?
Yes. Spire.Agent.Office supports flexible AI model integration and is compatible with mainstream AI infrastructure, including hosted model APIs and privately deployed models. You can point the agent at your own endpoint. See the integration tutorial for setup details; for questions about which providers are supported in your deployment, contact your account team at [email protected].
Which model does Spire.Agent.Office use for contract review?
Spire.Agent.Office connects to a large language model behind a SpireToken key. You describe the review or generation task in natural language, and the agent orchestrates the underlying document-processing tools. The model handles understanding; the document layer guarantees formatting and file fidelity.
Can it generate contracts in batches?
Yes. One contract template plus a data source such as an Excel sheet, and one instruction produces one contract per data row. Both field filling and placeholder replacement are supported. For the agent to pick up every row, keep the first row of the data source as the header, put one vendor per row, and avoid blank rows; if the number of generated contracts does not match the data rows, check the data source first.
Will the AI change my contract's formatting?
Not if you say so. Include a phrase like "preserve the original document layout, styling, and fonts" in your instruction; the official tutorial documents this exact fix.
How is this different from using a raw LLM API?
A raw LLM cannot reliably read, edit, or write Word and PDF files on its own; it needs a document-processing layer. A document AI agent pairs the LLM's language understanding with deterministic document APIs, so the output is a real, well-formed file.
Ready to Automate Your Contract Workflow?
Contract review and batch generation are the fastest places to get value: one template, one data source, one natural-language instruction, and real Word or PDF files out. Follow the Getting Started tutorial to run your first document workflow in .NET.
Further Reading
- Spire.Agent.Office product overview -- AI agent SDKs for every Office document format
- Generate Various Word Templates tutorial -- building templates the agent can fill
Automating Student Score Analysis and Ranking with Spire.Agent.Office
2026-08-07 07:50:53 Written by jie zouIn the field of education and academic affairs, processing exam scores after each test is one of the most frequent and time-consuming tasks. The same exam result often needs to be handled from two dimensions: for class students and class teachers, it needs to present the class's own score details, rankings, and subject strengths; for teachers and the academic affairs office, it needs cross-class horizontal comparison to determine which classes and subjects require focused attention.
The traditional approach usually requires manually writing formulas in Excel, sorting, drawing charts item by item, and writing analysis summaries. For different audiences, the same data must be reorganized twice, and the whole process often takes half a day to a full day. Formulas are error-prone, chart styles are inconsistent, and analysis criteria are hard to keep aligned.
Comparison with Traditional SDK API Processing
| Traditional Spire.Office for .NET API | Spire.Agent.Office Processing | |
|---|---|---|
| Driving Method | Write Excel formulas + file splitting + sorting + chart + conditional formatting code, controlling every step | Describe the goal in natural language; the AI understands and automatically orchestrates the execution path |
| Code Volume | Score analysis scenarios typically require 500-1000 lines of C# code (including per-class file splitting, formula calculation, ranking logic, chart configuration, etc.) | About 10 lines of calling code + one natural language instruction |
| Statistics Criteria | Must hard-code the calculation formulas and judgment logic for average/pass rate/excellence rate; adjusting criteria requires code changes | AI understands education statistics semantics and automatically computes by criteria such as "≥60 pass, ≥90 excellent" |
| Chart Generation | Must manually create Chart objects, configure data ranges, set chart types and styles | AI automatically selects the most appropriate chart type (radar, column, etc.) based on data semantics |
| Requirement Changes | Adding new statistics dimensions requires modifying code → compiling → deploying | Modify the description in the instruction; takes effect immediately |
This article introduces how to use the Excel AI capabilities of Spire.Agent.Office for two audiences — class students and teachers / the academic affairs office — to automate score statistics, ranking, and visual analysis with just a few natural language instructions.
For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The following examples assume Spire.Agent.Office is already installed and SpireToken is configured.
Class Score Statistics and Display
The score analysis for class students and class teachers focuses on the class itself: score details, in-class ranking, and subject strengths. Since there is no need for cross-class comparison, each class gets its own Excel file, which can be printed and posted, or used for parent meetings.
The following example uses the Spire.Agent.Office agent to automatically split data by class through natural language instructions and generate an independent score analysis Excel file for each class:
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// Source score data (containing class, student name, and subject score columns)
string inputPath = @"C:\ScoreAnalysis\StudentScores.xlsx";
// Result document path (null uses the output folder path set below)
string savePath = null;
// Output directory (one file per class)
string OutDir = @"C:\ScoreAnalysis\ClassAnalysis";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction =
"Process the input file as follows:\r\n" +
"1. Read the file and generate one separate Excel analysis file per class, named 'XXClassScoreAnalysis.xlsx'\r\n" +
"2. Each class file must contain: the class score details, class ranking by total score, per-subject average/max/min, pass rate (≥60 points), excellence rate (≥90 points), and score interval distribution\r\n" +
"3. Choose appropriate chart types to visualize the class performance\r\n" +
"4. Apply a unified and clean table style: highlight the top 10 by total score in green, and mark failing subject scores in red";
// AI generation
AIResult result = AnalyzeClassScores(instruction, inputPath, savePath, key, OutDir);
// AI-assisted score analysis
static AIResult AnalyzeClassScores(string instruction, string inputpath, string savePath, string key, string output)
{
// Configure the AI processing options
AIOptions options = new AIOptions();
options.SpireToken = key;
options.WorkDir = output;
using (Workbook wb = new Workbook())
{
if (!string.IsNullOrEmpty(inputpath) && File.Exists(inputpath))
wb.LoadFromFile(inputpath);
AIDocumentProcessor processor = wb.AI(options);
return processor.ExecuteInstruction(wb, instruction, savePath);
}
}
Original score data and per-class score analysis files

Grade Score Summary and Analysis
The score analysis for teachers and the academic affairs office focuses on the overall picture: gaps between classes, subjects that are weak across the board, and the distribution of the full-grade ranking. All classes' data must be consolidated into a single worksheet to enable horizontal comparison, unified criteria, and decision support.
The following example uses the Spire.Agent.Office agent to consolidate all classes' data into one worksheet through natural language instructions, completing class comparison and visual analysis:
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// Source score data (containing class, student name, and subject score columns)
string inputPath = @"C:\ScoreAnalysis\StudentScores.xlsx";
// Save path of the grade score analysis file
string savePath = @"C:\ScoreAnalysis\GradeAnalysis.xlsx";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction =
"Process the input file as follows:\r\n" +
"1. Read the file, and for each class calculate the average score, pass rate (≥60 points), and excellence rate (≥90 points) for every subject; generate a \"Class Comparison\" worksheet that summarizes these metrics for all classes.\r\n" +
"2. Generate the overall grade ranking based on total scores.\r\n" +
"3. Create radar charts for subject averages: one radar chart per class to show each class's own subject strengths, and a single combined radar chart that overlays all classes (each class as one series) for direct comparison.\r\n" +
"4. Based on the statistical data, analyze the overall performance of the entire grade, identify each class's strengths and weaknesses, and provide targeted improvement recommendations.";
// AI generation
AIResult result = AnalyzeGradeScores(instruction, inputPath, savePath, key);
// AI-assisted score analysis
static AIResult AnalyzeGradeScores(string instruction, string inputpath, string savePath, string key)
{
// Configure the AI processing options
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Workbook wb = new Workbook())
{
if (!string.IsNullOrEmpty(inputpath) && File.Exists(inputpath))
wb.LoadFromFile(inputpath);
AIDocumentProcessor processor = wb.AI(options);
return processor.ExecuteInstruction(wb, instruction, savePath);
}
}
Original score data and grade score analysis result

Comparison of the Two Approaches
| Class Score Statistics and Display | Grade Score Summary and Analysis | |
|---|---|---|
| Audience | Class students, class teachers | Teachers, academic affairs office |
| Output | One independent Excel file per class | All classes consolidated into one Excel file |
| Core Content | In-class score details, in-class ranking, per-subject statistics, subject strength charts | Cross-class comparison, full-grade ranking, radar charts, score analysis conclusions |
| Typical Uses | Print and post, parent meetings | Teaching research reports, teaching decisions, academic affairs statistics |
Frequently Asked Questions
The chart type is not as expected
Cause: The chart type selected by the AI may not match the user's presentation preferences.
Solution: Specify chart type preferences explicitly in the instruction, such as "use radar charts for class subject strengths, column charts for score interval distribution, and line charts for score trends across multiple tests."
How to handle tied rankings
Cause: It is normal for multiple students to have the same total score; the AI's default handling of tied ranks may not meet your requirements.
Solution: Specify the tie-breaking rule in the instruction, such as "when total scores are equal, sort by Computer Science score first."
Obtaining a SpireToken Key
- Contact [email protected] or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key
Configure it in code:
AIOptions options = new AIOptions();
options.SpireToken = key;
Generate PPT from Multi-Format Documents with Spire.Agent.Office
2026-08-03 03:09:15 Written by Lisa LiEfficiently transferring technical knowledge is a core challenge for every enterprise in day-to-day business. A large number of technical specification documents — such as operation manuals, safety and maintenance guides, and supply chain standard documents — are often dozens or even hundreds of pages long. How to quickly turn the core knowledge in these dense technical specifications into easy-to-understand PPT material is a key pain point in enterprise knowledge management.
This article demonstrates how to use the Spire.Agent.Office Presentation AI capability to analyze and summarize data sources in various formats, extract the core points, and generate professional PPT presentations.
- Generate PPT from a Word Document
- Generate PPT from a PDF Document
- Generate PPT from a Markdown Document
- Generate PPT from an Excel Document
Comparing with Traditional SDK/API Processing
| Traditional Spire.Office for .NET API | Spire.Agent.Office | |
|---|---|---|
| Driving approach | Requires calling the APIs of four products — Word, Excel, PDF, PowerPoint — extracting content from each document type via code, then calling the PowerPoint API to create slides page by page, add elements, and manually calculate layouts | Directly describe the requirement in natural language, and the AI understands and generates the PPT automatically |
| Development complexity | You need to be familiar with 4 different API sets, write separate parsing code for each format (.docx/.xlsx/.pdf), and then piece together the PowerPoint generation logic — large amount of code with high coupling | One natural-language instruction completes the entire workflow |
| Document parsing | You must manually specify which data to extract from each type of document; the parsing logic is hard-coded, and any document structure change requires synchronized code modification | AI automatically analyzes the document structure in depth and accurately extracts the key information |
| Versatility & maintainability | Each document format requires its own parsing logic; format changes or new document types require extensive code changes, with poor reusability | The same set of natural-language instructions adapts to different documents |
| Processing cycle | Several days (large documents require senior engineers to spend full time writing/debugging code) | Minutes (upload document + template + one instruction) |
Regarding product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The examples below assume that Spire.Agent.Office is installed and SpireToken is configured.
Generate PPT from a Word Document
Generate a minimalist-style PPT presentation based on the content of a Word document according to a natural-language instruction.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Presentation;
// Source data document
string inputPath = @"technical_requirements.docx";
// Result document path
string savePath = @"SafetyTechnicalRequirements.pptx";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction = "Extract the core points from 'technical_requirements.docx' to generate a PPT. 1. Ensure proper layout and formatting 2. Use a minimalist style with a light yellow theme 3. Generate 20 slides";
// AI generation
PPTGenerationResult result = GeneratePPT(inputPath, instruction, savePath, key);
// AI-assisted PPT generation
static PPTGenerationResult GeneratePPT(string input, string instruction, string savePath, string key)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
options.TimeoutMs = 1000000;
using (Presentation ppt = new Presentation())
{
AIDocumentProcessor processor = ppt.AI(options);
return processor.GeneratePresentation(input, instruction, savePath);
}
}

Generate PPT from a PDF Document
Automatically analyze the internal hierarchy of a PDF document, accurately extract the key information, and generate a retro-green themed PPT presentation according to the instruction.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Presentation;
// Source data document
string inputPath = @"procedures.pdf";
// Result document path
string savePath = @"SafetyOperationProcedures.pptx";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction = "Extract the key points from 'procedures.pdf' and generate a PPT. " +
"1. Ensure a well-structured layout and visual appeal; " +
"2. Include relevant diagrams and charts; " +
"3. Use a simple purple style as the theme; "+
"4. 9 pages";
// AI generation
PPTGenerationResult result = GeneratePPT(inputPath, instruction, savePath, key);
// AI-assisted PPT generation
static PPTGenerationResult GeneratePPT(string input, string instruction, string savePath, string key)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
options.TimeoutMs = 1000000;
using (Presentation ppt = new Presentation())
{
AIDocumentProcessor processor = ppt.AI(options);
return processor.GeneratePresentation(input, instruction, savePath);
}
}

Generate PPT from a Markdown Document
Automatically summarize the content of a Markdown-format data source and generate a tech-style PPT.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Presentation;
// Source data document
string inputPath = @"Management.md";
// Result document path
string savePath = @"SupplyChainManagement.pptx";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction = "Generate a PPT based on 'Management.md'. Requirements: 1. Adopt a tech/style; 2. Use light blue as the primary color scheme; 3. Ensure the core content is complete, with clear hierarchy and neat layout. Key data should be presented visually through charts and graphs.";
// AI generation
PPTGenerationResult result = GeneratePPT(inputPath, instruction, savePath, key);
// AI-assisted PPT generation
static PPTGenerationResult GeneratePPT(string input, string instruction, string savePath, string key)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
options.TimeoutMs = 1000000;
using (Presentation ppt = new Presentation())
{
AIDocumentProcessor processor = ppt.AI(options);
return processor.GeneratePresentation(input, instruction, savePath);
}
}

Generate PPT from an Excel Document
Automatically summarize the content of an Excel-format data source and generate a tech-style PPT.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Presentation;
// Source data document
string inputPath = @"data.xlsx";
// Result document path
string savePath = @"out.pptx";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction = "Generate a PPT based on data
.xlsx, 1. Ensure proper layout and formatting 2. Use a minimalist style with a light red theme 3. Ensure chart visual effects 4.Generate 15 pages";
// AI generation
PPTGenerationResult result = GeneratePPT(inputPath, instruction, savePath, key);
// AI-assisted PPT generation
static PPTGenerationResult GeneratePPT(string input, string instruction, string savePath, string key)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
options.TimeoutMs = 1000000;
using (Presentation ppt = new Presentation())
{
AIDocumentProcessor processor = ppt.AI(options);
return processor.GeneratePresentation(input, instruction, savePath);
}
}

FAQ
The number of generated PPT pages does not match the expectation
Cause: If the data source contains a large amount of content, the AI analysis will take more time. The default timeout of AIOptions.TimeoutMs is 5 minutes; if the analysis exceeds it, the AI analysis is interrupted.
Solution: Set AIOptions.TimeoutMs to a sufficiently large value, and also specify a page range in the instruction, e.g. "Keep the final PPT to 8-12 pages".
The key content extracted by AI is not accurate enough
Cause: The source document has a complex structure, and the AI may not have fully understood the hierarchy.
Solution: Explicitly specify the type of content to extract in the instruction, e.g. "Focus on extracting the data from the table in Chapter 2".
Get Your SpireToken Key
- Contact [email protected] or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key
Configure it in code:
AIProcessorOptions options = new AIProcessorOptions();
options.SpireToken = key;
Word templates are the foundation of enterprise business workflows. HR needs standard employment contracts and offer letters, sales teams need professional quotation and report templates, and administration needs unified meeting notices and certification documents. With the Word AI capabilities of Spire.Agent.Office, you simply describe the desired template style and content structure in natural language — for example, "Create a contract template with mail merge fields for 'Name, Position, Department, Salary, Start Date, End Date, Contract Type, Probation Period (months), Location'" and AI delivers the template directly.
Comparison with Traditional SDK API Approach
| Traditional Spire.Office for .NET API | Spire.Agent.Office | |
|---|---|---|
| Development Approach | Call APIs to build document structure line by line, paragraph by paragraph | Describe template style and structure in natural language; AI automatically composes and generates the complete template document |
| Code Volume | Hundreds of lines of document-building code per template | Just 1 natural language instruction |
| Style Adjustment | Font, color, border, and other styles require complex code-based formatting | Simply describe in natural language |
| Template Flexibility | Template structure changes require rewriting underlying document-building logic — high maintenance cost | Adjust the instruction description, AI regenerates — flexibly responds to changing requirements |
Several typical business scenario Word template examples:
- Word Employment Contract Template
- Word Quotation Template
- Word Certificate Template
- Budget Report Template
For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The examples below assume Spire.Agent.Office is already installed and SpireToken is configured.
Word Employment Contract Template
The most commonly used employment contracts in HR departments all share a relatively fixed structure: title, party information, main body clauses, signature section, etc.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;
string inputPath = @"";
// Result document path
string savePath = @"employmentContract.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
"Generate a Word employment contract template. " +
"The main title is 'Employment Contract', in No. 2 font size, bold, and centered. " +
"The body text uses Arial font throughout, in Small No. 4 font size (12pt), with a first-line indent of 2 characters per paragraph. " +
"Add a light blue watermark with the text 'E-iceblue' throughout the entire document. " +
"Include the following fields as mail merge fields: Name, Position/Department, Salary, Start Date, End Date, Contract Type, Probation Period (months), and Location. " +
"The overall style should be formal and professional, suitable for legal document scenarios.";
// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);
// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
// Create AI processor options instance
AIOptions options = new AIOptions();
options.SpireToken = key;
// Create Word document object
using (Document doc = new Document())
{
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// Create AI document processor instance
AIDocumentProcessor processor = doc.AI(options);
// Process the document according to the instruction and save the result to the specified path
return processor.ExecuteInstruction(doc, instruction, savePath);
}
}

Word Quotation Template
The most commonly used quotation templates in sales and business departments all share a relatively fixed structure: title, company information, client information, product quotation table, amount summary, quotation terms, signature section, etc.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;
string inputPath = @"";
// Result document path
string savePath = @"QuotationTemplate.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
"Generate a professional quotation template with the following styling requirements: " +
"Main title: 'Quotation' , font size equivalent to 26pt, bold, centered, using 'Arial' font. " +
"Body text: Calibri font, size 12pt , with 1.5× line spacing. " +
"Template structure must include: Company logo placeholder area, company information (address, phone number, email), client information (client name, contact person), product quotation table (including Serial Number, Product Name, Specifications, Quantity, Unit Price, Subtotal, Remarks), total price (in words + in digits), quotation validity period, company stamp/seal area. \n" +
"Use {{ }} as placeholder markers throughout the template, for example: {{Company Name}}, {{Client Name}}, {{Product Name}}, {{Unit Price}}, {{Quantity}}, {{Subtotal}}, {{Total Price in Words}}, {{Total Price in Digits}}.";
// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);
// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
// Create AI processor options instance
AIOptions options = new AIOptions();
options.SpireToken = key;
// Create Word document object
using (Document doc = new Document())
{
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// Create AI document processor instance
AIDocumentProcessor processor = doc.AI(options);
// Process the document according to the instruction and save the result to the specified path
return processor.ExecuteInstruction(doc, instruction, savePath);
}
}

Word Certificate Template
Certificate templates are widely used in scenarios such as training certification, commendation and awards, event participation, etc. Their core structure typically includes: certificate title (e.g., "Certificate of Honor", "Certificate of Completion"), certificate number, etc.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;
string inputPath = @"";
// Result document path
string savePath = @"WordCertificateTemplate.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
"Generate a one-page honor certificate template with the following style requirements: " +
"Overall classical and solemn style, with a gold double-line border, using Times New Roman font." +
"Centered at the top: certificate title 'CERTIFICATE OF HONOR' — 24pt, bold, gold color." +
"Center-aligned body layout with the following structure:" +
" Line 1: 'This is to certify that';" +
" Line 2: '{{Full Name}}' — bold, red color;" +
" Line 3: 'has demonstrated outstanding performance during the {{Year}} work year and is hereby awarded:';" +
" Line 4: '{{Honor Title}}' — bold, gold color;" +
" Line 5: 'This certificate is presented in recognition of this achievement.'." +
"Signatory area: bottom right, two lines right-aligned: '{{Issuing Authority}}' and '{{Date}}'." +
"Bottom left: certificate number displayed as 'No.: {{Certificate Number}}'." +
"Overall style: formal, solemn, and dignified, suitable for government or corporate honorary certificate presentations.";
// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);
// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
// Create AI processor options instance
AIOptions options = new AIOptions();
options.SpireToken = key;
// Create Word document object
using (Document doc = new Document())
{
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// Create AI document processor instance
AIDocumentProcessor processor = doc.AI(options);
// Process the document according to the instruction and save the result to the specified path
return processor.ExecuteInstruction(doc, instruction, savePath);
}
}

Budget Report Template
Budget report templates are commonly used document tools in enterprises or organizations for financial planning, project proposals, and annual planning. Their core structure typically includes: report title (e.g., "XX Annual Budget Report", "XX Project Budget Plan"), preparing unit and date, budget preparation notes, etc.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;
string inputPath = @"";
// Result document path
string savePath = @"BudgetReportTemplate.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
"Generate a professional budget report template with the following style requirements:" +
"Main title: '{{Year}} Annual Budget Report' — font size No.1 (approx. 26pt), bold, centered, using Arial." +
"Add a subtitle below the title: 'Prepared by: {{Department Name}} | Date: {{Preparation Date}}', font size No.4 small (approx. 12pt), centered." +
"The body is divided into four sections:\n" +
" Section 1 (Budget Overview): At the top, display four key metrics in a card-style horizontal layout with light background shading — 'Annual Budget Total: {{Total Budget}} ten-thousand yuan', 'Amount Executed: {{Executed Amount}} ten-thousand yuan', 'Execution Rate: {{Execution Rate}}%', 'Remaining Budget: {{Remaining Budget}} ten-thousand yuan'. The four data cards are placed side by side with numeric values bolded and enlarged.\n" +
" Section 2 (Detailed Budget Table): A detailed budget table with columns — Account Code, Account Name, Annual Budget (ten-thousand yuan), Q1 Execution, Q2 Execution, Q3 Execution, Q4 Execution, Total Executed, Execution Rate (%), Remaining Budget (ten-thousand yuan). Table header: dark green background (#1E5631), white bold font; all numeric columns: retain two decimal places; data rows: alternating row colors.\n" +
" Section 4 (Budget Notes): At the bottom of the page, add a 'Budget Notes' section — '{{Budget Preparation Notes}}'." +
"Overall style: formal, professional, and elegant — suitable for a formal budget report presented to management.";
// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);
// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
// Create AI processor options instance
AIOptions options = new AIOptions();
options.SpireToken = key;
// Create Word document object
using (Document doc = new Document())
{
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// Create AI document processor instance
AIDocumentProcessor processor = doc.AI(options);
// Process the document according to the instruction and save the result to the specified path
return processor.ExecuteInstruction(doc, instruction, savePath);
}
}

Frequently Asked Questions
Generated template style does not fully match expectations
Cause: The style description in the instruction is not specific enough.
Solution: Specify details such as font name explicitly in the instruction.
Already generated template needs modification
Cause: Business requirements have changed, requiring template adjustments.
Solution: Directly describe the modifications in the instruction and regenerate, or use the current document as input for AI secondary processing.
Generated template shows garbled Chinese characters or incorrect fonts
Cause: The font specified in the instruction is not installed on the system.
Solution: Ensure the font mentioned in the instruction is installed on the system, or use common system fonts in the instruction.
Getting a SpireToken Key
- Contact [email protected] or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key
Configure in code:
AIOptions options = new AIOptions();
options.SpireToken = key;
In enterprise HR scenarios, batch contract generation is one of the most common document processing needs — monthly new employee onboarding, contract renewals, labor agreement changes often involve processing dozens or even hundreds of contracts at once. Each contract needs personalized information such as employee name, position, salary, and contract term.
Comparison with Traditional SDK API Processing
| Traditional Spire.Office for .NET API | Spire.Agent.Office | |
|---|---|---|
| Approach | Write code for traditional API processing: load template → get fields → read data → fill row by row → save, every step requires code control | Describe the goal in natural language, AI automatically orchestrates and completes all processing steps |
| Code Volume | Requires dozens of lines of code for data reading, field mapping, loop writing, and format control | Only configuration code + 1 natural language instruction |
| Field Mapping | Hard-code the mapping between merge fields and Excel columns; data source changes require code updates | AI automatically understands semantic correspondence between column names and template fields; data source changes require no code changes |
| Flexibility | Template field changes require code changes → compilation → redeployment | Just adjust the template or data source; existing instructions are reusable |
| Maintainability | Relies on development team to maintain code | Templates and data sources can be maintained directly by business users |
This article introduces how to use Spire.Agent.Office Word AI capabilities to automatically write Excel employee data into Word templates and generate contracts in PDF format in batches, using both mail merge and placeholder replacement approaches. You are also free to save as DOCX, DOC, HTML, OFD, Markdown, XPS, and other formats to meet different archiving needs.
For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The following examples assume Spire.Agent.Office is already installed and SpireToken is configured.
Mail Merge Approach
Mail merge is the standard solution for batch Word document generation and the most commonly used pattern in HR scenarios. The core idea is: a contract template Word document with merge fields and a data source, letting AI complete the data-to-template merge.
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;
// Multiple document paths (data source files)
string[] attachmentPaths = new string[] { @"E:\data.xlsx" };
// Word template file path
string inputPath = @"E:\template-mailmerge.docx";
// Result document path (null here — will use the output folder path set below)
string savePath = null;
// Output directory
string OutDir = @"E:\output";
// SpireToken Key
string key = "**************************";
// Natural language instruction
string instruction =
"Execute mail merge: populate employee data from the attachment 'data.xlsx' into the merge fields of the contract template row by row; " +
"preserve the original document layout and styling after merging; " +
"generate one independent contract document per employee and save the output in PDF format";
// Call the Word document processing function
AIResult result = ExecuteDemoWord(instruction, inputPath, savePath, key, OutDir, attachmentPaths);
// Record processing log
WriteLog(result, "word", @"E:\log\");
// Execute Word document AI processing
static AIResult ExecuteDemoWord(string instruction, string inputPath, string savePath, string key, string output, string[] attachmentPaths)
{
// Create AIOptions configuration object
AIOptions options = new AIOptions();
// Set working directory to output directory
options.WorkDir = output;
// Set SpireToken Key
options.SpireToken = key;
// Use Document object to process Word document
using (Document doc = new Document())
{
// Load Word template from file
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// Create AI document processor
AIDocumentProcessor processor = doc.AI(options);
// Execute AI instruction
return processor.ExecuteInstruction(doc, instruction, savePath, attachmentPaths);
}
}
Original Word template (with mail merge fields) and Excel data
Output generated via mail merge 
Each generated contract fully preserves the template's formatting, table styles, and font settings, with all merge fields replaced by the corresponding employee data. If 50 new employees are being onboarded, just one template + one Excel file + one instruction is all it takes to generate all contracts.
Placeholder Replacement Approach
The placeholder replacement approach does not require predefining mail merge fields in the template. Instead, it uses custom placeholder markers (such as {{Name}}, {{Salary}}) directly in the document, which the AI agent identifies and replaces.
// Multiple document paths (data source files)
string[] attachmentPaths = new string[] { @"E:\data.xlsx" };
// Contract template file path
string inputPath = @"E:\template.docx";
// Save path (null here — will use the output folder path set below)
string savePath = null;
// Output directory
string OutDir = @"E:\output";
// SpireToken Key
string key = "**************************";
// Natural language instruction
string instruction =
"Read employee data from 'data.xlsx' and replace the corresponding placeholders in the contract template row by row" +
"Highlight the replaced field content, preserve the original document layout, styling, and fonts after replacement," +
"Generate one independent contract document per employee and save the output in PDF format";
// Call the AI Word document processing method
AIResult result = ExecuteDemoWord1(instruction, inputPath, savePath, key, OutDir, attachmentPaths);
// Record processing log
WriteLog(result, "word", @"E:\log\");
// Execute Word document AI processing
static AIResult ExecuteDemoWord(string instruction, string inputPath, string savePath, string key, string output, string[] attachmentPaths)
{
// Create AIOptions configuration object
AIOptions options = new AIOptions();
// Set working directory to output directory
options.WorkDir = output;
// Set SpireToken Key
options.SpireToken = key;
// Use Document object to process Word document
using (Document doc = new Document())
{
// Load Word template from file
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// Create AI document processor
AIDocumentProcessor processor = doc.AI(options);
// Execute AI instruction
return processor.ExecuteInstruction(doc, instruction, savePath, attachmentPaths);
}
}
Original Word template (with {{}} placeholders) and Excel data
Output generated via placeholder replacement 
Two Approaches Compared
| Mail Merge Approach | Placeholder Replacement Approach | |
|---|---|---|
| Template Creation | Requires inserting mail merge fields | Directly type {{}} placeholders |
| Learning Curve | Requires knowledge of Word mail merge functionality | Nearly zero learning cost |
| Flexibility | Fixed one-to-one field mapping | Supports dynamic calculation and formatting during replacement |
| Data Source | Requires structured data | Supports structured data, can also be defined in the instruction |
For creating Word templates with Spire.Agent.Office, please refer to the article "Creating Various Word Templates with Spire.Agent.Office".
Frequently Asked Questions
Generated document style changed
Cause: The AI model may modify or add content during processing.
Solution: Add a description like "preserve the original document layout, styling, and fonts" to the instruction.
Number of generated documents does not match the number of data rows after mail merge
Cause: Empty rows or merged cells in the data source Excel file, causing inaccurate row counting.
Solution: Ensure the first row of the data source contains column headers, with each subsequent row corresponding to one employee record and no empty rows in between. If the issue persists, add a sequence number column to the data source for validation.
Obtaining a SpireToken Key
- Contact [email protected] or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial or commercial API key.
Configure it in code:
AIOptions options = new AIOptions();
options.SpireToken = key;
Traditional Spire.Office for .NET workflows often require developers to have in-depth API knowledge and write extensive boilerplate code for tasks like formatting, extraction, and conversion. Spire.Agent.Office introduces an AI layer that abstracts this complexity, enabling you to accomplish these tasks using plain natural language instructions.
This tutorial walks you through integrating Spire.Agent.Office into a .NET 10 project(The product is based on NET Standard 2.1, compatible .NET 5/6/7/8 and other platforms, not limited to NET 10), enabling natural-language-powered document processing with minimal code.
- Why Choose Spire.Agent.Office
- Project Setup and Library Reference
- AI-Powered Document Processing
- Frequently Asked Questions
- Apply for SpireToken Key
Why Choose Spire.Agent.Office
Spire.Agent.Office is an AI agent built on top of the traditional Spire.Office for .NET document engine. The core differences are:
| Traditional Spire.Office for .NET | Spire.Agent.Office | |
|---|---|---|
| Operation | Manual coding (calling APIs, iterating document data, processing, saving results) | Natural language instructions (e.g., "Review this contract") |
| Low Learning Curve | Requires detailed API knowledge and object structure | Simply describe the requirements, AI executes automatically |
| Flexibility | API code may not suit all documents | Universal AI instructions handle all documents |
How It Works
Natural Language Instruction → Spire.Agent.Office AI Layer → Spire.Office Document Engine → Output File
Spire.Agent.Office parses your natural language instructions, converts them into internal calls to the Spire.Office document engine for processing, and ultimately generates the desired document. It supports processing and conversion of Word, Excel, PowerPoint, PDF, and other document formats.
Core Advantages
| Advantage | Description |
|---|---|
| AI-Native Experience | Replace complex API call chains with natural language for direct document processing |
| Stability and Reliability | Built on the mature Spire.Office document engine, ensuring reliable document processing |
| Seamless Integration | Cross-platform support, easy integration, flexible adaptation to business logic |
| Flexible AI Model Support | Compatible with mainstream AI infrastructure, ensuring accurate AI code generation |
| Accelerated Delivery | Reduces development time for document processing tasks |
Typical Use Cases
- Automated internal report generation and formatting
- Batch contract processing and data extraction
- Intelligent multi-format document conversion and distribution
- Automated meeting slide layout and export
Project Setup and Library Reference
Creating a .NET 10 Project

Installing Spire.Agent.Office via NuGet
After installing Spire.Agent.Office via NuGet, dependencies are installed automatically.

Importing Spire.Agent.Office Assemblies Locally
Download Spire.Agent.Office from the website, extract it to a local directory, and import it into the project.

When adding via local DLLs, the following dependencies are also required for optimal performance:
| Dependency Package | Minimum Version |
|---|---|
| coverlet.collector | >= 6.0.4 |
| Microsoft.CodeAnalysis | >= 4.5.0 |
| Microsoft.Data.Sqlite | >= 8.0.0 |
| Microsoft.Extensions.Caching.Memory | >= 8.0.0 |
| Microsoft.Extensions.Configuration | >= 8.0.0 |
| Microsoft.Extensions.Configuration.Abstractions | >= 8.0.0 |
| Microsoft.Extensions.Configuration.EnvironmentVariables | >= 8.0.0 |
| Microsoft.Extensions.Configuration.Json | >= 8.0.0 |
| Microsoft.Extensions.DependencyInjection | >= 8.0.0 |
| Microsoft.Extensions.Hosting.Abstractions | >= 8.0.0 |
| Microsoft.Extensions.Http | >= 8.0.0 |
| Microsoft.Extensions.Http.Polly | >= 8.0.0 |
| Microsoft.Extensions.Logging | >= 8.0.0 |
| Microsoft.Extensions.Logging.Abstractions | >= 8.0.0 |
| Microsoft.Extensions.Logging.Console | >= 8.0.0 |
| Microsoft.Extensions.Options | >= 8.0.0 |
| Microsoft.ML.OnnxRuntime | >= 1.16.1 |
| Microsoft.NET.Test.Sdk | >= 17.12.0 |
| Polly | >= 8.0.0 |
| Polly.Extensions.Http | >= 3.0.0 |
| PolySharp | >= 1.4.0 |
| Serilog | >= 4.3.0 |
| Serilog.Extensions.Logging | >= 7.0.0 |
| Serilog.Sinks.File | >= 6.0.0 |
| SkiaSharp | >= 3.116.1 |
| Spire.Docfor.NETStandard | >= 14.8.0 |
| Spire.PDFfor.NETStandard | >= 12.8.3 |
| Spire.Presentationfor.NETStandard | >= 11.8.2 |
| Spire.XLSfor.NETStandard | >= 16.8.2 |
| System.Text.Json | >= 10.0.10 |
| xunit | >= 2.9.2 |
| xunit.runner.visualstudio | >= 2.8.2 |
AI-Powered Document Processing
Core Workflow
Document AI processing follows this pattern:
- Create a document object (Workbook / Document / PdfDocument / Presentation)
- Load a preset document (optional; can start with an empty document)
- Configure AIOptions (set SpireToken)
- Call
.AI(options)to obtain an AIDocumentProcessor - Execute AI instructions and monitor execution status:
- Processing existing documents: Call
AIDocumentProcessor.ExecuteInstruction(), returnsAIResult - Generating PPT documents: Call
AIDocumentProcessor.GeneratePresentation(), returnsGenerationResult
- Processing existing documents: Call
Core Code
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Pdf;
using Spire.Doc;
using Spire.Presentation;
using Spire.Xls;
// Excel Processing
static AIResult ExecuteDemoXls(string instruction, string inputPath, string savePath, string key, string[] attachmentPaths)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Workbook workbook = new Workbook())
{
// Load the document if the input path exists and the file is accessible
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
workbook.LoadFromFile(inputPath);
}
// Otherwise, use an empty Workbook
AIDocumentProcessor processor = workbook.AI(options);
return processor.ExecuteInstruction(workbook, instruction, savePath, attachmentPaths);
}
}
// Word Processing
static AIResult ExecuteDemoWord(string instruction, string inputPath, string savePath, string key, string[] attachmentPaths)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Document doc = new Document())
{
// Load the document if the input path exists and the file is accessible
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// Otherwise, use an empty Document
AIDocumentProcessor processor = doc.AI(options);
return processor.ExecuteInstruction(doc, instruction, savePath, attachmentPaths);
}
}
// PDF Processing
static AIResult ExecuteDemoPDF(string instruction, string inputPath, string savePath, string key, string[] attachmentPaths)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
using (PdfDocument pdf = new PdfDocument())
{
// Load the document if the input path exists and the file is accessible
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
pdf.LoadFromFile(inputPath);
}
// Otherwise, use an empty PdfDocument
AIDocumentProcessor processor = pdf.AI(options);
return processor.ExecuteInstruction(pdf, instruction, savePath, attachmentPaths);
}
}
// PPT Generation
static PPTGenerationResult GeneratPPT(string input, string instruction, string savePath, string key)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Presentation ppt = new Presentation())
{
AIDocumentProcessor processor = ppt.AI(options);
return processor.GeneratePresentation(input, instruction, savePath);
}
}
// Based on existing PPT processing
static AIResult ExecuteDemoPPT(string inputPath, string instruction, string savePath, string key, string[] attachmentPaths)
{
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Presentation ppt = new Presentation())
{
// Load the document if the input path exists and the file is accessible
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
ppt.LoadFromFile(inputPath);
}
// Otherwise, use an empty Presentation
AIDocumentProcessor processor = ppt.AI(options);
return processor.ExecuteInstruction(ppt, instruction, savePath, attachmentPaths);
}
}
// Write execution log
static void WriteLog(dynamic? aiResult, string taskName, string basePath)
{
string logFilePath = Path.Combine(basePath, $"{taskName}.txt");
string? logDir = Path.GetDirectoryName(logFilePath);
if (!string.IsNullOrEmpty(logDir) && !Directory.Exists(logDir))
Directory.CreateDirectory(logDir);
var logBuilder = new System.Text.StringBuilder();
// Determine execution status: Success/Failure/Skipped
string status = aiResult == null ? "SKIPPED" :
aiResult.Success ? "SUCCESS" : $"FAILED: {aiResult.ErrorMessage}";
logBuilder.AppendLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{taskName}] {status}");
if (aiResult != null)
{
// Log execution duration
logBuilder.AppendLine($" | Duration: {aiResult.Duration.TotalSeconds:F2}s");
// Log token usage statistics
var tu = aiResult.TokenUsage;
if (tu != null)
{
logBuilder.Append($" | In: {tu.InputTokens:N0}"); // Input tokens
logBuilder.Append($" | Out: {tu.OutputTokens:N0}"); // Output tokens
logBuilder.Append($" | CacheR: {tu.CacheReadTokens:N0}"); // Cache read tokens
logBuilder.Append($" | CacheW: {tu.CacheWriteTokens:N0}"); // Cache write tokens
logBuilder.Append($" | CacheT: {tu.TotalCacheTokens:N0}"); // Total cache tokens
logBuilder.Append($" | Total: {tu.TotalTokens:N0}"); // Total tokens
}
}
logBuilder.AppendLine();
File.AppendAllText(logFilePath, logBuilder.ToString());
}
Calling AI Processing
The following examples demonstrate using natural language interaction to leverage the system's powerful document processing capabilities for various complex document tasks.
// Multiple document paths
string[] attachmentPaths = new string[] { };
// Word Processing
string inputPath = @"in.docx";
string savePath = @"out.pdf";
string key = "SpireToken key";
string instruction = "Find '****' and highlight it, save result to PDF";
AIResult result = ExecuteDemoWord(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "word", @"log\");
// PPT Processing
string inputPath = @"in.pptx";
string savePath = @"out.pptx";
string key = "SpireToken key";
string instruction = "Add notes description to each slide";
AIResult result = ExecuteDemoPPT(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "ppt", @"log\");
// PPT Generation
string inputPath = @"AI.md";
string savePath = @"out.pptx";
string key = "SpireToken key";
string instruction = "Generate a PPT based on AI.md";
PPTGenerationResult result = GeneratPPT(inputPath, instruction, savePath, key);
WriteLog(result, "ppt", @"log\");
// PDF Processing
string inputPath = @"in.pdf";
string savePath = @"out.md";
string key = "SpireToken key";
string instruction = "Extract table data and save as standard markdown format";
AIResult result = ExecuteDemoPDF(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "pdf", @"log\");
// Excel Processing
string inputPath = @"in.xlsx";
string savePath = @"out.pdf";
string key = "SpireToken key";
string instruction = "Delete empty rows in the document";
AIResult result = ExecuteDemoXls(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "xls", @"log\");
Frequently Asked Questions
SpireToken Key Not Configured Properly
If the SpireToken Key is not configured, is incorrect, or has expired, Spire.Agent.Office will throw an exception and the program will abort. Ensure the SpireToken Key is valid before proceeding.
AI Instruction Execution Failed
The AIResult returned by ExecuteInstruction may contain failure information. Check the Success property.
AIResult result = processor.ExecuteInstruction(doc, instruction, outputPath);
if (result == null || !result.Success)
{
throw new InvalidOperationException(
$"AI instruction failed: {result?.ErrorMessage ?? "Unknown error"}");
}
Incorrect Document Path
If processing an existing document, an incorrect file path will cause document loading to fail:
- Ensure the document path is correct
- For multi-document operations (e.g., document merging), additional documents can be defined in
attachmentPaths
Apply for SpireToken Key
Spire.Agent.Office requires a valid SpireToken Key to experience full functionality:
- Contact [email protected] or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial or commercial API key
Configure it in your code:
AIOptions options = new AIOptions();
options.SpireToken = key;