在传统的 Spire.Office for .NET 组件文档处理场景中,开发者需要熟悉产品 API 接口编写大量代码来实现格式设置、数据提取、文档转换等操作。Spire.Agent.Office 通过引入 AI 层使用 自然语言指令 来完成这些任务,告别繁琐的代码编写。
本教程将介绍如何在 .NET 10 项目中集成使用 Spire.Agent.Office 实现文档处理的 AI 化。
为什么选择 Spire.Agent.Office
Spire.Agent.Office 是基于 Spire.Office for .NET 传统 API 文档引擎之上构建的 AI 智能体,与传统的 Spire.Office for .NET 组件的核心区别在于:
| 传统 Spire.Office for .NET | Spire.Agent.Office | |
|---|---|---|
| 操作方式 | 手写代码(调用 API 接口、遍历文档数据、操作处理、保存结果) | 自然语言指令(如 "合同审查") |
| 使用门槛 | 需要了解详细的 API 和对象结构 | 只需描述需求,AI 自动执行 |
| 灵活性 | API 代码处理可能不适合所有文档 | 通用 AI 指令可以处理所有文档 |
工作原理
自然语言指令 → Spire.Agent.Office AI 层 → Spire.Office 文档引擎 → 输出文件
Spire.Agent.Office 解析您的自然语言指令,将其转换为 Spire.Office 文档引擎的内部调用处理文档,最终生成预期文档,支持 Word、Excel、PowerPoint、PDF 等多种文档格式处理和转换。
核心优势
| 优势 | 说明 |
|---|---|
| AI 原生体验 | 告别繁琐的 API 调用链,用自然语言直接实现文档处理 |
| 稳定可靠性 | 基于成熟的 Spire.Office 文档引擎构建,保证文档处理的效果 |
| 无缝集成 | 支持跨平台使用,轻松集成,可灵活对接业务逻辑,实现功能拓展需求 |
| 灵活 AI 模型支持 | 兼容主流 AI 基础设施,保证 AI 代码生成准确率 |
| 加速开发交付 | 缩短文档处理任务开发时间 |
项目搭建与库引用
创建 .NET 10 平台的项目

通过 NuGet 安装 Spire.Agent.Office 产品
NuGet 安装 Spire.Agent.Office后相应依赖会自动安装

通过本地导入 Spire.Agent.Office 程序集
从网站下载 Spire.Agent.Office解压至本地目录后导入项目

通过本地 Dll 添加,需要同时添加以下依赖,以保证更好的运行效果:
| 依赖包 | 最低版本 |
|---|---|
| Microsoft.Win32.Registry | >= 5.0.0 |
| System.Drawing.Common | >= 10.0.0 |
| System.Text.Encoding.CodePages | >= 10.0.0 |
| HarfBuzzSharp | >= 8.3.0.1 |
| coverlet.collector | >= 6.0.2 |
| Microsoft.Extensions.DependencyInjection | >= 10.0.3 |
| Microsoft.Extensions.DependencyInjection.Abstractions | >= 10.0.3 |
| Microsoft.Extensions.Logging | >= 10.0.3 |
| Microsoft.Extensions.Logging.Abstractions | >= 10.0.3 |
| Microsoft.Extensions.Logging.Console | >= 10.0.3 |
| Microsoft.Extensions.Options | >= 10.0.3 |
| Microsoft.Extensions.Hosting | >= 10.0.3 |
| Microsoft.Extensions.Caching.Memory | >= 10.0.3 |
| Microsoft.Extensions.Http | >= 10.0.3 |
| Microsoft.Extensions.Http.Polly | >= 10.0.3 |
| Microsoft.DotNet.Interactive | >= 1.0.0-beta.23403.1 |
| Microsoft.DotNet.Interactive.CSharp | >= 1.0.0-beta.23403.1 |
| Microsoft.CodeAnalysis.CSharp | >= 4.5.0 |
| Microsoft.CodeAnalysis.CSharp.Workspaces | >= 4.5.0 |
| Microsoft.CodeAnalysis.CSharp.Scripting | >= 4.5.0 |
| Microsoft.CodeAnalysis.Workspaces.MSBuild | >= 4.5.0 |
| Microsoft.Extensions.Configuration.EnvironmentVariables | >= 10.0.8 |
| Microsoft.Extensions.Configuration.Json | >= 10.0.8 |
| Microsoft.NET.Test.Sdk | >= 17.12.0 |
| Polly | >= 8.5.0 |
| Polly.Extensions.Http | >= 3.0.0 |
| Serilog | >= 4.2.0 |
| Serilog.Sinks.File | >= 7.0.0 |
| Serilog.Extensions.Logging | >= 10.0.0 |
| Microsoft.Data.Sqlite | >= 8.0.0 |
| Dapper | >= 2.1.35 |
| Microsoft.ML.OnnxRuntime | >= 1.17.3 |
| SkiaSharp | >= 3.116.1 |
| System.Text.Json | >= 10.0.0 |
| xunit | >= 2.9.2 |
| xunit.runner.visualstudio | >= 2.8.2 |
| FluentAssertions | >= 7.1.0 |
| Spire.Doc for.NETStandard | >= 14.6.13 |
| Spire.PDF for.NETStandard | >= 12.6.9 |
| Spire.Presentation for.NETStandard | >= 16.6.3 |
| Spire.XLS for.NETStandard | >= 11.6.11 |
文档处理 AI 化的实现
核心流程
文档 AI 处理主要遵循以下模式:
- 创建文档对象(Workbook / Document / PdfDocument / Presentation)
- 加载预设文档(可选,也可以为空新创建文档)
- AIOptions 配置(设置 SpireToken)
- 调用
.AI(options)获取 AIDocumentProcessor - 执行 AI 指令,并根据返回监测执行状态:
- 处理现有文档:调用
AIDocumentProcessor.ExecuteInstruction(),返回AIResult - 生成 PPT 文档:调用
AIDocumentProcessor.GeneratePresentation(),返回GenerationResult
- 处理现有文档:调用
核心代码
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Pdf;
using Spire.Doc;
using Spire.Presentation;
using Spire.Xls;
// Excel 处理
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())
{
// 如果输入路径存在且文件可访问,则加载文档
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
workbook.LoadFromFile(inputPath);
}
// 否则使用空 Workbook
AIDocumentProcessor processor = workbook.AI(options);
return processor.ExecuteInstruction(workbook, instruction, savePath, attachmentPaths);
}
}
// Word 处理
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())
{
// 如果输入路径存在且文件可访问,则加载文档
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
doc.LoadFromFile(inputPath);
}
// 否则使用空 Document
AIDocumentProcessor processor = doc.AI(options);
return processor.ExecuteInstruction(doc, instruction, savePath, attachmentPaths);
}
}
// PDF 处理
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())
{
// 如果输入路径存在且文件可访问,则加载文档
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
pdf.LoadFromFile(inputPath);
}
// 否则使用空 PdfDocument
AIDocumentProcessor processor = pdf.AI(options);
return processor.ExecuteInstruction(pdf, instruction, savePath, attachmentPaths);
}
}
// PPT 生成
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);
}
}
// 基于现有 PPT 的处理
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())
{
// 如果输入路径存在且文件可访问,则加载文档
if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
{
ppt.LoadFromFile(inputPath);
}
// 否则使用空 Presentation
AIDocumentProcessor processor = ppt.AI(options);
return processor.ExecuteInstruction(ppt, instruction, savePath, attachmentPaths);
}
}
// 写入日志
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();
// 判断执行状态:成功/失败/跳过
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)
{
// 记录执行耗时
logBuilder.AppendLine($" | Duration: {aiResult.Duration.TotalSeconds:F2}s");
// 记录 Token 使用统计
var tu = aiResult.TokenUsage;
if (tu != null)
{
logBuilder.Append($" | In: {tu.InputTokens:N0}"); // 输入 Token 数
logBuilder.Append($" | Out: {tu.OutputTokens:N0}"); // 输出 Token 数
logBuilder.Append($" | CacheR: {tu.CacheReadTokens:N0}"); // 缓存读取 Token 数
logBuilder.Append($" | CacheW: {tu.CacheWriteTokens:N0}"); // 缓存写入 Token 数
logBuilder.Append($" | CacheT: {tu.TotalCacheTokens:N0}"); // 缓存总 Token 数
logBuilder.Append($" | Total: {tu.TotalTokens:N0}"); // 总 Token 数
}
}
logBuilder.AppendLine();
File.AppendAllText(logFilePath, logBuilder.ToString());
}
调用进行 AI 处理
如下面示例,以自然语言为交互方式,调用系统强大的文档处理能力,完成各类复杂的文档任务。
// 多个文档路径添加
string[] attachmentPaths = new string[] { };
// 针对 Word 处理
string inputPath = @"in.docx";
string savePath = @"out.pdf";
string key = "SpireToken key";
string instruction = "查找 '****' 进行高亮,结果保存到 PDF";
AIResult result = ExecuteDemoWord(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "word", @"log\");
// 针对 PPT 处理
string inputPath = @"in.pptx";
string savePath = @"out.pptx";
string key = "SpireToken key";
string instruction = "将 PPT 每页添加 notes 描述";
AIResult result = ExecuteDemoPPT(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "ppt", @"log\");
// PPT 生成
string inputPath = @"AI.md";
string savePath = @"out.pptx";
string key = "SpireToken key";
string instruction = "根据 AI.md 生成 PPT 文档";
PPTGenerationResult result = GeneratPPT(inputPath, instruction, savePath, key);
WriteLog(result, "ppt", @"log\");
// 针对 PDF 处理
string inputPath = @"in.pdf";
string savePath = @"out.md";
string key = "SpireToken key";
string instruction = "提取表格数据保存为标准的 markdown 格式";
AIResult result = ExecuteDemoPDF(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "pdf", @"log\");
// Excel 处理
string inputPath = @"in.xlsx";
string savePath = @"out.pdf";
string key = "SpireToken key";
string instruction = "将文档中空行删除";
AIResult result = ExecuteDemoXls(instruction, inputPath, savePath, key, attachmentPaths);
WriteLog(result, "xls", @"log\");
常见错误处理
SpireToken Key 未正确配置
如果未配置 SpireToken Key,配置的 Key 不正确或者 Key 已失效,Spire.Agent.Office 会抛出异常,程序将中止执行。请先确保 SpireToken Key 的正确有效性。
AI 指令执行失败
ExecuteInstruction 返回的 AIResult 可能包含失败信息,需要检查 Success 属性。
AIResult result = processor.ExecuteInstruction(doc, instruction, outputPath);
if (result == null || !result.Success)
{
throw new InvalidOperationException(
$"AI instruction failed: {result?.ErrorMessage ?? "Unknown error"}");
}
加载文档路径不正确
如果针对已有文档处理,文件路径不正确会导致加载文档失败:
- 保证正确的文档路径
- 如果需要针对多文档操作(例如文档合并),其它文档可定义在
attachmentPaths中
申请 SpireToken Key
Spire.Agent.Office 需要配置有效的 SpireToken Key 才能体验完整的功能:
- 联系 该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。或访问 https://www.e-iceblue.com/TemLicense.html获得试用/商业 API 密钥
在代码中配置:
AIOptions options = new AIOptions();options.SpireToken = key;









