Aspose.Words for .NET下载地址 https://soft51.cc/software/175811283999782847
文档模板是现代办公自动化的核心组件,它不仅能够提高文档制作效率,还能确保企业文档的一致性和专业性。Aspose.Words for .NET 提供了强大的模板管理功能,支持模板创建、变量替换、主题应用、动态生成等多种特性。本教程将深入探讨模板与主题系统的关键技术和实践应用。
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Tables;
using System;
using System.Drawing;
class TemplateBasics
{
static void Main()
{
// 创建报告模板
CreateReportTemplate();
// 创建信函模板
CreateLetterTemplate();
// 使用模板创建文档
UseTemplateToCreateDocument();
Console.WriteLine("模板创建和使用完成!");
}
static void CreateReportTemplate()
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
// 设置页面边距
template.FirstSection.PageSetup.TopMargin = 72;
template.FirstSection.PageSetup.BottomMargin = 72;
template.FirstSection.PageSetup.LeftMargin = 90;
template.FirstSection.PageSetup.RightMargin = 90;
// 创建页眉
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Size = 10;
builder.Font.Color = Color.Gray;
builder.Write("企业季度报告");
builder.InsertParagraph();
builder.InsertHorizontalRule();
// 回到文档主体
builder.MoveToDocumentEnd();
// 创建标题区域
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Name = "微软雅黑";
builder.Font.Size = 24;
builder.Font.Bold = true;
builder.Font.Color = Color.FromArgb(0, 70, 130);
builder.Writeln("{{REPORT_TITLE}}");
builder.Font.Size = 16;
builder.Font.Bold = false;
builder.Font.Color = Color.Gray;
builder.Writeln("{{REPORT_PERIOD}}");
builder.InsertParagraph();
// 创建摘要部分
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Size = 18;
builder.Font.Bold = true;
builder.Font.Color = Color.FromArgb(0, 70, 130);
builder.Writeln("执行摘要");
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Font.Color = Color.Black;
builder.ParagraphFormat.FirstLineIndent = 24;
builder.Writeln("{{EXECUTIVE_SUMMARY}}");
// 创建数据表格
builder.InsertParagraph();
builder.ParagraphFormat.FirstLineIndent = 0;
builder.Font.Size = 18;
builder.Font.Bold = true;
builder.Font.Color = Color.FromArgb(0, 70, 130);
builder.Writeln("关键数据");
CreateDataTable(builder);
// 创建页脚
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 10;
builder.Font.Color = Color.Gray;
builder.Write("第 ");
builder.InsertField("PAGE", "");
builder.Write(" 页,共 ");
builder.InsertField("NUMPAGES", "");
builder.Write(" 页");
template.Save("企业报告模板.dotx");
}
static void CreateDataTable(DocumentBuilder builder)
{
Table table = builder.StartTable();
// 表头
string[] headers = { "指标", "当前值", "目标值", "完成率" };
foreach (string header in headers)
{
builder.InsertCell();
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(0, 70, 130);
builder.Font.Color = Color.White;
builder.Font.Bold = true;
builder.Write(header);
}
builder.EndRow();
// 数据行
for (int i = 1; i <= 3; i++)
{
builder.InsertCell();
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.Write($"{{{{METRIC_{i}_NAME}}}}");
builder.InsertCell();
builder.Write($"{{{{METRIC_{i}_CURRENT}}}}");
builder.InsertCell();
builder.Write($"{{{{METRIC_{i}_TARGET}}}}");
builder.InsertCell();
builder.Write($"{{{{METRIC_{i}_COMPLETION}}}}");
builder.EndRow();
}
builder.EndTable();
}
static void CreateLetterTemplate()
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
// 公司抬头
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Name = "微软雅黑";
builder.Font.Size = 20;
builder.Font.Bold = true;
builder.Font.Color = Color.FromArgb(0, 70, 130);
builder.Writeln("{{COMPANY_NAME}}");
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Font.Color = Color.Black;
builder.Writeln("{{COMPANY_ADDRESS}}");
builder.Writeln("电话:{{COMPANY_PHONE}} | 邮箱:{{COMPANY_EMAIL}}");
builder.InsertParagraph();
builder.InsertHorizontalRule();
builder.InsertParagraph();
// 日期和收信人
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Writeln("{{LETTER_DATE}}");
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.InsertParagraph();
builder.Writeln("{{RECIPIENT_NAME}}");
builder.Writeln("{{RECIPIENT_ADDRESS}}");
builder.InsertParagraph();
// 称呼和正文
builder.Writeln("尊敬的 {{RECIPIENT_SALUTATION}}:");
builder.InsertParagraph();
builder.ParagraphFormat.FirstLineIndent = 24;
builder.Writeln("{{LETTER_BODY}}");
// 结尾
builder.InsertParagraph();
builder.ParagraphFormat.FirstLineIndent = 0;
builder.Writeln("此致");
builder.Writeln("敬礼!");
builder.InsertParagraph();
builder.Writeln("{{SENDER_NAME}}");
builder.Writeln("{{SENDER_TITLE}}");
template.Save("商务信函模板.dotx");
}
static void UseTemplateToCreateDocument()
{
Document doc = new Document("企业报告模板.dotx");
// 替换变量
doc.Range.Replace("{{REPORT_TITLE}}", "2024年第一季度销售报告", new FindReplaceOptions());
doc.Range.Replace("{{REPORT_PERIOD}}", "2024年1月-3月", new FindReplaceOptions());
doc.Range.Replace("{{EXECUTIVE_SUMMARY}}", "本季度公司销售业绩表现优异,较去年同期增长15%。", new FindReplaceOptions());
// 替换表格数据
doc.Range.Replace("{{METRIC_1_NAME}}", "销售额", new FindReplaceOptions());
doc.Range.Replace("{{METRIC_1_CURRENT}}", "500万", new FindReplaceOptions());
doc.Range.Replace("{{METRIC_1_TARGET}}", "450万", new FindReplaceOptions());
doc.Range.Replace("{{METRIC_1_COMPLETION}}", "111%", new FindReplaceOptions());
doc.Save("季度销售报告.docx");
}
}
using Aspose.Words;
using Aspose.Words.Replacing;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class AdvancedTemplateProcessor
{
private Document document;
private Dictionary<string, object> variables;
public AdvancedTemplateProcessor(string templatePath)
{
document = new Document(templatePath);
variables = new Dictionary<string, object>();
}
public void SetVariable(string name, object value)
{
variables[name] = value;
}
public void SetVariables(Dictionary<string, object> vars)
{
foreach (var kvp in vars)
{
variables[kvp.Key] = kvp.Value;
}
}
// 处理基本变量
public void ProcessBasicVariables()
{
foreach (var kvp in variables)
{
string placeholder = $"{{{{{kvp.Key}}}}}";
string value = FormatValue(kvp.Value);
document.Range.Replace(placeholder, value, new FindReplaceOptions());
}
}
// 处理条件变量
public void ProcessConditionalVariables()
{
var regex = new Regex(@"\{\{IF\s+(\w+)\}\}(.*?)\{\{/IF\}\}", RegexOptions.Singleline);
var matches = regex.Matches(document.Range.Text);
foreach (Match match in matches)
{
string variableName = match.Groups[1].Value;
string content = match.Groups[2].Value;
string replacement = "";
if (variables.ContainsKey(variableName) &&
variables[variableName] != null &&
!string.IsNullOrEmpty(variables[variableName].ToString()))
{
replacement = content;
}
document.Range.Replace(match.Value, replacement, new FindReplaceOptions());
}
}
// 处理循环变量
public void ProcessLoopVariables()
{
var regex = new Regex(@"\{\{LOOP\s+(\w+)\}\}(.*?)\{\{/LOOP\}\}", RegexOptions.Singleline);
var matches = regex.Matches(document.Range.Text);
foreach (Match match in matches)
{
string listName = match.Groups[1].Value;
string template = match.Groups[2].Value;
string replacement = "";
if (variables.ContainsKey(listName) &&
variables[listName] is List<Dictionary<string, object>> list)
{
foreach (var item in list)
{
string itemContent = template;
foreach (var kvp in item)
{
itemContent = itemContent.Replace($"{{{{{kvp.Key}}}}}", kvp.Value?.ToString() ?? "");
}
replacement += itemContent;
}
}
document.Range.Replace(match.Value, replacement, new FindReplaceOptions());
}
}
public void SaveAs(string filePath)
{
ProcessConditionalVariables();
ProcessLoopVariables();
ProcessBasicVariables();
document.Save(filePath);
}
private string FormatValue(object value)
{
return value switch
{
DateTime dateTime => dateTime.ToString("yyyy年MM月dd日"),
decimal d => d.ToString("N2"),
double d => d.ToString("N2"),
float f => f.ToString("N2"),
null => "",
_ => value.ToString()
};
}
static void DemoAdvancedTemplate()
{
// 创建包含高级占位符的模板
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
builder.Writeln("项目报告:{{PROJECT_NAME}}");
builder.Writeln("报告日期:{{REPORT_DATE}}");
builder.InsertParagraph();
builder.Writeln("{{IF HAS_SUMMARY}}");
builder.Writeln("项目概述:{{PROJECT_SUMMARY}}");
builder.Writeln("{{/IF}}");
builder.InsertParagraph();
builder.Writeln("团队成员:");
builder.Writeln("{{LOOP TEAM_MEMBERS}}");
builder.Writeln("- {{NAME}}:{{ROLE}}");
builder.Writeln("{{/LOOP}}");
template.Save("高级模板示例.dotx");
// 使用高级模板处理器
var processor = new AdvancedTemplateProcessor("高级模板示例.dotx");
processor.SetVariable("PROJECT_NAME", "企业管理系统开发");
processor.SetVariable("REPORT_DATE", DateTime.Now);
processor.SetVariable("HAS_SUMMARY", "true");
processor.SetVariable("PROJECT_SUMMARY", "本项目旨在开发一套完整的企业管理信息系统");
var teamMembers = new List<Dictionary<string, object>>
{
new Dictionary<string, object> { {"NAME", "张三"}, {"ROLE", "项目经理"} },
new Dictionary<string, object> { {"NAME", "李四"}, {"ROLE", "开发工程师"} },
new Dictionary<string, object> { {"NAME", "王五"}, {"ROLE", "测试工程师"} }
};
processor.SetVariable("TEAM_MEMBERS", teamMembers);
processor.SaveAs("项目报告生成.docx");
Console.WriteLine("高级模板处理完成!");
}
}
using Aspose.Words;
using Aspose.Words.Themes;
using System;
using System.Drawing;
class ThemeManager
{
public static void CreateAndApplyThemes()
{
// 创建企业蓝色主题
CreateCorporateBlueTheme();
// 创建自然绿色主题
CreateNatureGreenTheme();
// 演示主题应用
ApplyThemeToDocument();
Console.WriteLine("主题创建和应用完成!");
}
static void CreateCorporateBlueTheme()
{
Document doc = new Document();
var theme = doc.Theme;
// 设置主题名称
theme.Name = "企业蓝色";
// 配置主题颜色
theme.Colors[ThemeColor.Accent1] = Color.FromArgb(0, 70, 130); // 主要色
theme.Colors[ThemeColor.Accent2] = Color.FromArgb(0, 120, 180); // 次要色
theme.Colors[ThemeColor.Accent3] = Color.FromArgb(100, 150, 200); // 辅助色1
theme.Colors[ThemeColor.Accent4] = Color.FromArgb(200, 220, 240); // 辅助色2
theme.Colors[ThemeColor.Accent5] = Color.FromArgb(255, 165, 0); // 强调色
theme.Colors[ThemeColor.Dark1] = Color.FromArgb(33, 33, 33); // 主要文本色
theme.Colors[ThemeColor.Light1] = Color.White; // 背景色
// 配置主题字体
theme.MajorFonts.Latin = "微软雅黑";
theme.MinorFonts.Latin = "宋体";
// 应用主题到样式
ApplyThemeToStyles(doc);
// 创建示例内容
DocumentBuilder builder = new DocumentBuilder(doc);
CreateThemeDemo(builder, "企业蓝色主题演示");
doc.Save("企业蓝色主题.docx");
}
static void CreateNatureGreenTheme()
{
Document doc = new Document();
var theme = doc.Theme;
theme.Name = "自然绿色";
theme.Colors[ThemeColor.Accent1] = Color.FromArgb(76, 175, 80);
theme.Colors[ThemeColor.Accent2] = Color.FromArgb(129, 199, 132);
theme.Colors[ThemeColor.Accent3] = Color.FromArgb(165, 214, 167);
theme.Colors[ThemeColor.Accent4] = Color.FromArgb(200, 230, 201);
theme.Colors[ThemeColor.Accent5] = Color.FromArgb(255, 193, 7);
theme.Colors[ThemeColor.Dark1] = Color.FromArgb(46, 125, 50);
theme.MajorFonts.Latin = "Segoe UI";
theme.MinorFonts.Latin = "Segoe UI";
ApplyThemeToStyles(doc);
DocumentBuilder builder = new DocumentBuilder(doc);
CreateThemeDemo(builder, "自然绿色主题演示");
doc.Save("自然绿色主题.docx");
}
static void ApplyThemeToStyles(Document document)
{
// 标题样式使用主题字体和颜色
var heading1 = document.Styles[StyleIdentifier.Heading1];
heading1.Font.ThemeFont = ThemeFont.Major;
heading1.Font.ThemeColor = ThemeColor.Accent1;
heading1.Font.Size = 18;
var heading2 = document.Styles[StyleIdentifier.Heading2];
heading2.Font.ThemeFont = ThemeFont.Major;
heading2.Font.ThemeColor = ThemeColor.Accent2;
heading2.Font.Size = 16;
// 正文样式
var normal = document.Styles[StyleIdentifier.Normal];
normal.Font.ThemeFont = ThemeFont.Minor;
normal.Font.ThemeColor = ThemeColor.Dark1;
normal.Font.Size = 12;
// 创建自定义主题样式
CreateCustomThemeStyles(document);
}
static void CreateCustomThemeStyles(Document document)
{
// 强调框样式
var emphasisBox = document.Styles.Add(StyleType.Paragraph, "主题强调框");
emphasisBox.Font.ThemeFont = ThemeFont.Minor;
emphasisBox.Font.ThemeColor = ThemeColor.Dark1;
emphasisBox.ParagraphFormat.Shading.BackgroundThemeColor = ThemeColor.Accent4;
emphasisBox.ParagraphFormat.Borders.LineStyle = LineStyle.Single;
emphasisBox.ParagraphFormat.Borders.ThemeColor = ThemeColor.Accent1;
emphasisBox.ParagraphFormat.LeftIndent = 20;
emphasisBox.ParagraphFormat.RightIndent = 20;
emphasisBox.ParagraphFormat.SpaceBefore = 10;
emphasisBox.ParagraphFormat.SpaceAfter = 10;
// 标题栏样式
var titleBar = document.Styles.Add(StyleType.Paragraph, "主题标题栏");
titleBar.Font.ThemeFont = ThemeFont.Major;
titleBar.Font.ThemeColor = ThemeColor.Light1;
titleBar.Font.Bold = true;
titleBar.Font.Size = 14;
titleBar.ParagraphFormat.Shading.BackgroundThemeColor = ThemeColor.Accent1;
titleBar.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// 重要提示样式
var importantNote = document.Styles.Add(StyleType.Character, "重要提示");
importantNote.Font.ThemeFont = ThemeFont.Minor;
importantNote.Font.ThemeColor = ThemeColor.Accent5;
importantNote.Font.Bold = true;
}
static void CreateThemeDemo(DocumentBuilder builder, string title)
{
builder.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln(title);
builder.ParagraphFormat.StyleName = "Heading 2";
builder.Writeln("主题颜色演示");
builder.ParagraphFormat.StyleName = "主题强调框";
builder.Writeln("这是使用主题颜色的强调框,展示了主题背景色和边框色的应用。");
builder.ParagraphFormat.StyleName = "主题标题栏";
builder.Writeln("主题标题栏样式");
builder.ParagraphFormat.StyleName = "Normal";
builder.Write("正文中包含");
builder.Font.StyleName = "重要提示";
builder.Write("重要提示");
builder.Font.StyleName = "Normal";
builder.Write("样式的文本,展示主题字符样式的效果。");
}
static void ApplyThemeToDocument()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// 应用企业主题
CreateCorporateTheme(doc);
builder.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln("主题应用演示文档");
builder.ParagraphFormat.StyleName = "Normal";
builder.Writeln("这个文档展示了如何通过主题系统统一管理文档的视觉风格。");
doc.Save("主题应用演示.docx");
}
static void CreateCorporateTheme(Document document)
{
var theme = document.Theme;
theme.Colors[ThemeColor.Accent1] = Color.FromArgb(0, 70, 130);
theme.MajorFonts.Latin = "微软雅黑";
theme.MinorFonts.Latin = "宋体";
ApplyThemeToStyles(document);
}
}
using Aspose.Words;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
public class TemplateLibrary
{
private string libraryPath;
private List<TemplateInfo> templates;
public TemplateLibrary(string path)
{
libraryPath = path;
templates = new List<TemplateInfo>();
Directory.CreateDirectory(libraryPath);
LoadTemplateIndex();
}
// 注册模板
public void RegisterTemplate(string filePath, TemplateMetadata metadata)
{
var templateInfo = new TemplateInfo
{
Id = Guid.NewGuid().ToString(),
FileName = Path.GetFileName(filePath),
Name = metadata.Name,
Category = metadata.Category,
Description = metadata.Description,
Author = metadata.Author,
CreatedDate = DateTime.Now,
Tags = metadata.Tags
};
string destPath = Path.Combine(libraryPath, templateInfo.FileName);
File.Copy(filePath, destPath, true);
templates.Add(templateInfo);
SaveTemplateIndex();
Console.WriteLine($"模板 '{templateInfo.Name}' 已注册");
}
// 搜索模板
public List<TemplateInfo> SearchTemplates(string keyword = null, string category = null)
{
var results = templates.AsEnumerable();
if (!string.IsNullOrEmpty(keyword))
{
results = results.Where(t =>
t.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
t.Description.Contains(keyword, StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(category))
{
results = results.Where(t => t.Category.Equals(category, StringComparison.OrdinalIgnoreCase));
}
return results.ToList();
}
// 获取模板
public Document GetTemplate(string templateId)
{
var templateInfo = templates.FirstOrDefault(t => t.Id == templateId);
if (templateInfo == null)
throw new ArgumentException($"模板 ID {templateId} 不存在");
string templatePath = Path.Combine(libraryPath, templateInfo.FileName);
return new Document(templatePath);
}
// 基于模板创建文档
public Document CreateFromTemplate(string templateId, Dictionary<string, object> variables = null)
{
var document = GetTemplate(templateId);
if (variables != null)
{
foreach (var kvp in variables)
{
string placeholder = $"{{{{{kvp.Key}}}}}";
string value = kvp.Value?.ToString() ?? "";
document.Range.Replace(placeholder, value, new FindReplaceOptions());
}
}
return document;
}
// 获取所有分类
public List<string> GetCategories()
{
return templates.Select(t => t.Category).Distinct().ToList();
}
private void LoadTemplateIndex()
{
string indexPath = Path.Combine(libraryPath, "index.json");
if (File.Exists(indexPath))
{
string json = File.ReadAllText(indexPath);
templates = JsonSerializer.Deserialize<List<TemplateInfo>>(json) ?? new List<TemplateInfo>();
}
}
private void SaveTemplateIndex()
{
string indexPath = Path.Combine(libraryPath, "index.json");
var options = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string json = JsonSerializer.Serialize(templates, options);
File.WriteAllText(indexPath, json);
}
// 使用示例
public static void DemoTemplateLibrary()
{
var library = new TemplateLibrary(@"C:\TemplateLibrary");
// 创建示例模板
CreateSampleTemplates(library);
// 演示模板使用
UseSampleTemplates(library);
Console.WriteLine("模板库演示完成!");
}
static void CreateSampleTemplates(TemplateLibrary library)
{
// 创建会议纪要模板
Document meetingTemplate = new Document();
DocumentBuilder builder = new DocumentBuilder(meetingTemplate);
builder.Font.Size = 18;
builder.Font.Bold = true;
builder.Writeln("会议纪要");
builder.InsertParagraph();
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Writeln("会议主题:{{MEETING_TOPIC}}");
builder.Writeln("会议时间:{{MEETING_DATE}}");
builder.Writeln("会议地点:{{MEETING_LOCATION}}");
builder.Writeln("参会人员:{{ATTENDEES}}");
builder.InsertParagraph();
builder.Writeln("会议内容:");
builder.Writeln("{{MEETING_CONTENT}}");
meetingTemplate.Save("会议纪要模板.dotx");
// 注册到库
library.RegisterTemplate("会议纪要模板.dotx", new TemplateMetadata
{
Name = "标准会议纪要",
Category = "办公文档",
Description = "适用于各种会议的标准纪要模板",
Author = "办公室",
Tags = new List<string> { "会议", "纪要", "办公" }
});
// 创建项目报告模板
Document projectTemplate = new Document();
builder = new DocumentBuilder(projectTemplate);
builder.Font.Size = 20;
builder.Font.Bold = true;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Writeln("{{PROJECT_NAME}}");
builder.Writeln("项目进度报告");
builder.InsertParagraph();
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Writeln("报告期间:{{REPORT_PERIOD}}");
builder.Writeln("项目负责人:{{PROJECT_MANAGER}}");
builder.InsertParagraph();
builder.Writeln("项目进展:{{PROJECT_PROGRESS}}");
builder.Writeln("存在问题:{{ISSUES}}");
builder.Writeln("下步计划:{{NEXT_STEPS}}");
projectTemplate.Save("项目报告模板.dotx");
library.RegisterTemplate("项目报告模板.dotx", new TemplateMetadata
{
Name = "项目进度报告",
Category = "项目管理",
Description = "项目进度跟踪报告模板",
Author = "项目部",
Tags = new List<string> { "项目", "进度", "报告" }
});
}
static void UseSampleTemplates(TemplateLibrary library)
{
Console.WriteLine("\n=== 模板库使用演示 ===");
// 搜索模板
var allTemplates = library.SearchTemplates();
Console.WriteLine($"库中共有 {allTemplates.Count} 个模板:");
foreach (var template in allTemplates)
{
Console.WriteLine($"- {template.Name} ({template.Category})");
}
// 使用模板创建文档
if (allTemplates.Any())
{
var meetingTemplate = allTemplates.First(t => t.Name.Contains("会议"));
var variables = new Dictionary<string, object>
{
{"MEETING_TOPIC", "月度工作总结会议"},
{"MEETING_DATE", "2024年3月15日"},
{"MEETING_LOCATION", "会议室A"},
{"ATTENDEES", "张三、李四、王五"},
{"MEETING_CONTENT", "本月工作完成情况良好,下月重点推进新项目启动。"}
};
var document = library.CreateFromTemplate(meetingTemplate.Id, variables);
document.Save("月度总结会议纪要.docx");
Console.WriteLine("已生成会议纪要文档");
}
}
}
// 支持类定义
public class TemplateInfo
{
public string Id { get; set; }
public string FileName { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public string Author { get; set; }
public DateTime CreatedDate { get; set; }
public List<string> Tags { get; set; } = new List<string>();
}
public class TemplateMetadata
{
public string Name { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public string Author { get; set; }
public List<string> Tags { get; set; } = new List<string>();
}
using Aspose.Words;
using Aspose.Words.Tables;
using System;
using System.Collections.Generic;
using System.Drawing;
public class DynamicTemplateGenerator
{
// 根据数据结构生成表格模板
public static Document GenerateTableTemplate(string templateName, List<ColumnDefinition> columns)
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
// 标题
builder.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln($"{templateName}");
builder.Writeln("生成日期:{{GENERATED_DATE}}");
builder.InsertParagraph();
// 创建表格
Table table = builder.StartTable();
// 表头
foreach (var column in columns)
{
builder.InsertCell();
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(0, 70, 130);
builder.Font.Color = Color.White;
builder.Font.Bold = true;
builder.Write(column.Header);
}
builder.EndRow();
// 数据行模板
builder.InsertCell();
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.Write("{{LOOP DATA_ROWS}}");
builder.EndRow();
foreach (var column in columns)
{
builder.InsertCell();
string placeholder = FormatPlaceholder(column);
builder.Write(placeholder);
}
builder.EndRow();
builder.InsertCell();
builder.Write("{{/LOOP}}");
builder.EndRow();
builder.EndTable();
// 汇总信息
builder.InsertParagraph();
builder.Writeln("总记录数:{{TOTAL_RECORDS}}");
return template;
}
// 根据表单字段生成表单模板
public static Document GenerateFormTemplate(string formName, List<FormFieldInfo> fields)
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
// 表单标题
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 18;
builder.Font.Bold = true;
builder.Writeln(formName);
builder.InsertParagraph();
// 生成表单字段
foreach (var field in fields)
{
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Bold = true;
builder.Write(field.Label);
if (field.Required)
{
builder.Font.Color = Color.Red;
builder.Write(" *");
builder.Font.Color = Color.Black;
}
builder.Font.Bold = false;
builder.InsertParagraph();
CreateFormField(builder, field);
builder.InsertParagraph();
}
// 提交信息
builder.InsertParagraph();
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Size = 10;
builder.Writeln("提交人:{{SUBMITTER}}");
builder.Writeln("提交时间:{{SUBMIT_DATE}}");
return template;
}
// 生成报告模板
public static Document GenerateReportTemplate(ReportStructure structure)
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
// 报告封面
CreateReportCover(builder, structure);
// 报告章节
foreach (var section in structure.Sections)
{
builder.InsertBreak(BreakType.PageBreak);
CreateReportSection(builder, section);
}
return template;
}
private static string FormatPlaceholder(ColumnDefinition column)
{
return column.DataType switch
{
DataType.Currency => $"{{{{FORMAT_CURRENCY({column.FieldName})}}}}",
DataType.Date => $"{{{{FORMAT_DATE({column.FieldName})}}}}",
DataType.Percentage => $"{{{{FORMAT_PERCENT({column.FieldName})}}}}",
_ => $"{{{{{column.FieldName}}}}}"
};
}
private static void CreateFormField(DocumentBuilder builder, FormFieldInfo field)
{
switch (field.Type)
{
case FormFieldType.Text:
builder.Write($"___________________ ({field.Placeholder ?? "请输入"})");
break;
case FormFieldType.MultilineText:
builder.Write("{{MULTILINE_" + field.Name + "}}");
break;
case FormFieldType.Checkbox:
foreach (var option in field.Options)
{
builder.Write($"☐ {option} ");
}
break;
case FormFieldType.RadioButton:
foreach (var option in field.Options)
{
builder.Write($"○ {option} ");
}
break;
case FormFieldType.Date:
builder.Write("____年____月____日");
break;
}
}
private static void CreateReportCover(DocumentBuilder builder, ReportStructure structure)
{
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 24;
builder.Font.Bold = true;
builder.Writeln("{{COMPANY_NAME}}");
builder.InsertParagraph();
builder.Font.Size = 20;
builder.Writeln(structure.Title);
builder.Font.Size = 16;
builder.Font.Bold = false;
builder.Writeln("{{REPORT_PERIOD}}");
builder.InsertParagraph();
builder.Font.Size = 12;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Writeln("编制日期:{{REPORT_DATE}}");
builder.Writeln("编制部门:{{DEPARTMENT}}");
}
private static void CreateReportSection(DocumentBuilder builder, ReportSection section)
{
builder.Font.Size = 16;
builder.Font.Bold = true;
builder.Writeln($"{section.Number} {section.Title}");
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.InsertParagraph();
builder.Writeln($"{{{{SECTION_{section.Number}_CONTENT}}}}");
if (section.IncludeChart)
{
builder.InsertParagraph();
builder.Writeln($"{{{{CHART_{section.Number}}}}}");
}
if (section.IncludeTable)
{
builder.InsertParagraph();
builder.Writeln($"{{{{TABLE_{section.Number}}}}}");
}
}
// 使用示例
public static void DemoDynamicGeneration()
{
// 生成员工表格模板
var columns = new List<ColumnDefinition>
{
new ColumnDefinition { Header = "姓名", FieldName = "NAME" },
new ColumnDefinition { Header = "部门", FieldName = "DEPARTMENT" },
new ColumnDefinition { Header = "薪资", FieldName = "SALARY", DataType = DataType.Currency },
new ColumnDefinition { Header = "入职日期", FieldName = "HIRE_DATE", DataType = DataType.Date }
};
var tableTemplate = GenerateTableTemplate("员工信息表", columns);
tableTemplate.Save("动态员工表模板.docx");
// 生成申请表单模板
var fields = new List<FormFieldInfo>
{
new FormFieldInfo
{
Name = "NAME",
Label = "姓名",
Type = FormFieldType.Text,
Required = true
},
new FormFieldInfo
{
Name = "GENDER",
Label = "性别",
Type = FormFieldType.RadioButton,
Options = new List<string> { "男", "女" }
},
new FormFieldInfo
{
Name = "BIRTH_DATE",
Label = "出生日期",
Type = FormFieldType.Date
},
new FormFieldInfo
{
Name = "EXPERIENCE",
Label = "工作经历",
Type = FormFieldType.MultilineText
}
};
var formTemplate = GenerateFormTemplate("员工入职申请表", fields);
formTemplate.Save("动态申请表模板.docx");
// 生成报告模板
var reportStructure = new ReportStructure
{
Title = "季度业绩报告",
Sections = new List<ReportSection>
{
new ReportSection { Number = "1", Title = "执行摘要" },
new ReportSection { Number = "2", Title = "财务数据", IncludeChart = true, IncludeTable = true },
new ReportSection { Number = "3", Title = "市场分析", IncludeChart = true }
}
};
var reportTemplate = GenerateReportTemplate(reportStructure);
reportTemplate.Save("动态报告模板.docx");
Console.WriteLine("动态模板生成完成!");
}
}
// 支持类
public class ColumnDefinition
{
public string Header { get; set; }
public string FieldName { get; set; }
public DataType DataType { get; set; } = DataType.Text;
}
public class FormFieldInfo
{
public string Name { get; set; }
public string Label { get; set; }
public FormFieldType Type { get; set; }
public bool Required { get; set; }
public string Placeholder { get; set; }
public List<string> Options { get; set; } = new List<string>();
}
public class ReportStructure
{
public string Title { get; set; }
public List<ReportSection> Sections { get; set; } = new List<ReportSection>();
}
public class ReportSection
{
public string Number { get; set; }
public string Title { get; set; }
public bool IncludeChart { get; set; }
public bool IncludeTable { get; set; }
}
public enum DataType { Text, Currency, Date, Percentage }
public enum FormFieldType { Text, MultilineText, Checkbox, RadioButton, Date }
using Aspose.Words;
using System;
using System.Collections.Generic;
using System.Drawing;
public class EnterpriseStandardization
{
private EnterpriseStandards standards;
public EnterpriseStandardization(EnterpriseStandards enterpriseStandards)
{
standards = enterpriseStandards;
}
// 创建标准化模板套件
public void CreateStandardTemplatesSuite()
{
Console.WriteLine("正在创建企业标准化模板套件...");
CreateStandardLetterTemplate();
CreateStandardReportTemplate();
CreateStandardMemoTemplate();
CreateStandardContractTemplate();
Console.WriteLine("企业标准化模板套件创建完成!");
}
private void CreateStandardLetterTemplate()
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
ApplyStandardPageSetup(template);
CreateCorporateLetterhead(builder);
// 信件内容
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Name = standards.BodyFont;
builder.Font.Size = 12;
builder.Writeln("{{LETTER_DATE}}");
builder.InsertParagraph();
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Writeln("{{RECIPIENT_NAME}}");
builder.Writeln("{{RECIPIENT_ADDRESS}}");
builder.InsertParagraph();
builder.Writeln("尊敬的 {{RECIPIENT_SALUTATION}}:");
builder.InsertParagraph();
builder.ParagraphFormat.FirstLineIndent = standards.ParagraphIndent;
builder.Writeln("{{LETTER_BODY}}");
builder.InsertParagraph();
builder.ParagraphFormat.FirstLineIndent = 0;
builder.Writeln("此致");
builder.Writeln("敬礼!");
builder.InsertParagraph();
builder.Writeln("{{SENDER_NAME}}");
builder.Writeln("{{SENDER_TITLE}}");
CreateCorporateFooter(builder);
template.Save("企业标准信函模板.dotx");
}
private void CreateStandardReportTemplate()
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
ApplyStandardPageSetup(template);
// 报告封面
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Name = standards.HeadingFont;
builder.Font.Size = 24;
builder.Font.Bold = true;
builder.Font.Color = standards.PrimaryColor;
builder.Writeln(standards.CompanyName);
builder.InsertParagraph();
builder.Font.Size = 20;
builder.Writeln("{{REPORT_TITLE}}");
builder.Font.Size = 16;
builder.Font.Bold = false;
builder.Writeln("{{REPORT_PERIOD}}");
builder.InsertBreak(BreakType.PageBreak);
// 报告内容结构
ApplyStandardHeadingStyle(builder, 1);
builder.Writeln("1. 执行摘要");
ApplyStandardBodyStyle(builder);
builder.Writeln("{{EXECUTIVE_SUMMARY}}");
builder.InsertParagraph();
ApplyStandardHeadingStyle(builder, 1);
builder.Writeln("2. 详细分析");
ApplyStandardBodyStyle(builder);
builder.Writeln("{{DETAILED_ANALYSIS}}");
builder.InsertParagraph();
ApplyStandardHeadingStyle(builder, 1);
builder.Writeln("3. 结论与建议");
ApplyStandardBodyStyle(builder);
builder.Writeln("{{CONCLUSIONS}}");
template.Save("企业标准报告模板.dotx");
}
private void CreateStandardMemoTemplate()
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
ApplyStandardPageSetup(template);
// 备忘录标题
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Name = standards.HeadingFont;
builder.Font.Size = 18;
builder.Font.Bold = true;
builder.Font.Color = standards.PrimaryColor;
builder.Writeln("内部备忘录");
builder.InsertParagraph();
builder.InsertHorizontalRule();
builder.InsertParagraph();
// 备忘录信息
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Size = 12;
builder.Font.Bold = true;
builder.Write("收件人:");
builder.Font.Bold = false;
builder.Writeln("{{TO}}");
builder.Font.Bold = true;
builder.Write("发件人:");
builder.Font.Bold = false;
builder.Writeln("{{FROM}}");
builder.Font.Bold = true;
builder.Write("日期:");
builder.Font.Bold = false;
builder.Writeln("{{DATE}}");
builder.Font.Bold = true;
builder.Write("主题:");
builder.Font.Bold = false;
builder.Writeln("{{SUBJECT}}");
builder.InsertParagraph();
builder.InsertHorizontalRule();
builder.InsertParagraph();
ApplyStandardBodyStyle(builder);
builder.Writeln("{{MEMO_CONTENT}}");
template.Save("企业标准备忘录模板.dotx");
}
private void CreateStandardContractTemplate()
{
Document template = new Document();
DocumentBuilder builder = new DocumentBuilder(template);
ApplyStandardPageSetup(template);
// 合同标题
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Name = standards.HeadingFont;
builder.Font.Size = 22;
builder.Font.Bold = true;
builder.Writeln("{{CONTRACT_TITLE}}");
builder.InsertParagraph();
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Writeln("合同编号:{{CONTRACT_NUMBER}}");
builder.InsertParagraph();
// 甲乙双方
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
ApplyStandardBodyStyle(builder);
builder.Font.Bold = true;
builder.Writeln("甲方:");
builder.Font.Bold = false;
builder.Writeln("单位名称:{{PARTY_A_NAME}}");
builder.Writeln("法定代表人:{{PARTY_A_LEGAL_REP}}");
builder.Writeln("地址:{{PARTY_A_ADDRESS}}");
builder.InsertParagraph();
builder.Font.Bold = true;
builder.Writeln("乙方:");
builder.Font.Bold = false;
builder.Writeln("单位名称:{{PARTY_B_NAME}}");
builder.Writeln("法定代表人:{{PARTY_B_LEGAL_REP}}");
builder.Writeln("地址:{{PARTY_B_ADDRESS}}");
builder.InsertParagraph();
// 合同条款
for (int i = 1; i <= 5; i++)
{
builder.Font.Bold = true;
builder.Writeln($"第{NumberToChinese(i)}条 {{{{CLAUSE_{i}_TITLE}}}}");
builder.Font.Bold = false;
builder.Writeln($"{{{{CLAUSE_{i}_CONTENT}}}}");
builder.InsertParagraph();
}
// 签署区域
builder.Font.Bold = true;
builder.Writeln("甲方(盖章): 乙方(盖章):");
builder.InsertParagraph();
builder.Font.Bold = false;
builder.Writeln("签字: 签字:");
builder.InsertParagraph();
builder.Writeln("日期:{{SIGN_DATE}} 日期:{{SIGN_DATE}}");
template.Save("企业标准合同模板.dotx");
}
// 应用标准页面设置
private void ApplyStandardPageSetup(Document document)
{
var pageSetup = document.FirstSection.PageSetup;
pageSetup.TopMargin = 72; // 1英寸
pageSetup.BottomMargin = 72;
pageSetup.LeftMargin = 90; // 1.25英寸
pageSetup.RightMargin = 90;
}
// 应用标准标题样式
private void ApplyStandardHeadingStyle(DocumentBuilder builder, int level)
{
builder.Font.Name = standards.HeadingFont;
builder.Font.Color = standards.PrimaryColor;
builder.Font.Bold = true;
builder.Font.Size = level == 1 ? 16 : 14;
builder.ParagraphFormat.SpaceBefore = 12;
builder.ParagraphFormat.SpaceAfter = 6;
builder.ParagraphFormat.FirstLineIndent = 0;
}
// 应用标准正文样式
private void ApplyStandardBodyStyle(DocumentBuilder builder)
{
builder.Font.Name = standards.BodyFont;
builder.Font.Size = 12;
builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.ParagraphFormat.LineSpacing = 18;
builder.ParagraphFormat.SpaceAfter = 6;
builder.ParagraphFormat.FirstLineIndent = standards.ParagraphIndent;
}
// 创建企业信头
private void CreateCorporateLetterhead(DocumentBuilder builder)
{
builder.Font.Name = standards.HeadingFont;
builder.Font.Size = 16;
builder.Font.Bold = true;
builder.Font.Color = standards.PrimaryColor;
builder.Writeln(standards.CompanyName);
builder.Font.Size = 10;
builder.Font.Bold = false;
builder.Font.Color = Color.Black;
builder.Writeln(standards.CompanyAddress);
builder.Writeln($"电话:{standards.CompanyPhone} | 邮箱:{standards.CompanyEmail}");
builder.InsertParagraph();
builder.InsertHorizontalRule();
builder.InsertParagraph();
}
// 创建企业页脚
private void CreateCorporateFooter(DocumentBuilder builder)
{
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 9;
builder.Font.Color = Color.Gray;
builder.InsertHorizontalRule();
builder.Write($"{standards.CompanyName} | 第 ");
builder.InsertField("PAGE", "");
builder.Write(" 页");
}
// 数字转中文
private string NumberToChinese(int number)
{
string[] chinese = { "", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
return number <= 10 ? chinese[number] : number.ToString();
}
// 使用示例
public static void DemoEnterpriseStandardization()
{
var standards = new EnterpriseStandards
{
CompanyName = "创新科技有限公司",
CompanyAddress = "上海市浦东新区科技园区123号",
CompanyPhone = "+86-21-12345678",
CompanyEmail = "contact@innovate-tech.com",
PrimaryColor = Color.FromArgb(0, 70, 130),
HeadingFont = "微软雅黑",
BodyFont = "宋体",
ParagraphIndent = 24
};
var standardization = new EnterpriseStandardization(standards);
standardization.CreateStandardTemplatesSuite();
Console.WriteLine("企业模板标准化完成!");
}
}
// 企业标准配置类
public class EnterpriseStandards
{
public string CompanyName { get; set; } = "示例企业有限公司";
public string CompanyAddress { get; set; } = "中国北京市示例区示例路888号";
public string CompanyPhone { get; set; } = "+86-10-88888888";
public string CompanyEmail { get; set; } = "info@example.com";
public Color PrimaryColor { get; set; } = Color.FromArgb(0, 70, 130);
public string HeadingFont { get; set; } = "微软雅黑";
public string BodyFont { get; set; } = "宋体";
public double ParagraphIndent { get; set; } = 24;
}
// 主程序示例
class Program
{
static void Main()
{
Console.WriteLine("=== Aspose.Words 模板与主题管理教程 ===\n");
// 基础模板创建
TemplateBasics.Main();
// 高级变量处理
AdvancedTemplateProcessor.DemoAdvancedTemplate();
// 主题管理
ThemeManager.CreateAndApplyThemes();
// 模板库管理
TemplateLibrary.DemoTemplateLibrary();
// 动态模板生成
DynamicTemplateGenerator.DemoDynamicGeneration();
// 企业标准化
EnterpriseStandardization.DemoEnterpriseStandardization();
Console.WriteLine("\n所有示例运行完成!");
}
}
本教程全面介绍了 Aspose.Words for .NET 中的模板与主题管理系统,涵盖了从基础到高级的完整解决方案:
Aspose.Words for .NET下载地址 https://soft51.cc/software/175811283999782847