.NET駕馭Word之力:玩轉文本與格式
在前面的文章中,我們已經了解了Word對象模型的核心組件,包括Application、Document和Range對象。掌握了這些基礎知識后,我們現在可以進一步深入到文檔內容的處理,特別是文本的插入和格式化操作。
本文將詳細介紹如何使用MudTools.OfficeInterop.Word庫來操作Word文檔中的文本內容,包括多種插入文本的方法、字體格式設置和段落格式設置。最后,我們將通過一個實戰示例,創建一個格式規范的商業信函模板,來綜合運用所學知識。
3.1 插入文本的多種方式
在Word文檔自動化處理中,插入文本是最基本也是最重要的操作之一。MudTools.OfficeInterop.Word提供了多種方式來插入文本,每種方式都有其適用場景。
使用 Range.Text 屬性
Range對象是Word對象模型中最核心的組件之一,它代表文檔中的一個連續區域。通過設置Range.Text屬性,我們可以輕松地在指定位置插入或替換文本。
// 獲取文檔的整個內容范圍
var range = document.Content;
// 在文檔末尾插入文本
range.Collapse(WdCollapseDirection.wdCollapseEnd);
range.Text = "這是通過Range.Text屬性插入的文本。\n";
// 替換文檔中的所有內容
range.Text = "這是替換后的全新內容。";
Range.Text屬性是最直接的文本操作方式,適合于需要精確控制文本位置的場景。
應用場景:動態報告生成
在企業環境中,經常需要根據數據動態生成報告。例如,財務部門需要每月生成財務報告,其中包含關鍵指標數據。
using MudTools.OfficeInterop;
using MudTools.OfficeInterop.Word;
using System;
using System.Collections.Generic;
// 財務數據模型
public class FinancialData
{
public string Department { get; set; }
public decimal Revenue { get; set; }
public decimal Expenses { get; set; }
public decimal Profit => Revenue - Expenses;
public double GrowthRate { get; set; }
}
// 財務報告生成器
public class FinancialReportGenerator
{
/// <summary>
/// 生成財務報告
/// </summary>
/// <param name="data">財務數據列表</param>
/// <param name="reportMonth">報告月份</param>
public void GenerateFinancialReport(List<FinancialData> data, DateTime reportMonth)
{
try
{
// 使用模板創建報告文檔
using var wordApp = WordFactory.CreateFrom(@"C:\Templates\FinancialReportTemplate.dotx");
var document = wordApp.ActiveDocument;
// 隱藏Word應用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 替換報告標題中的月份信息
document.FindAndReplace("[MONTH]", reportMonth.ToString("yyyy年MM月"));
// 定位到數據表格位置
var tableBookmark = document.Bookmarks["FinancialDataTable"];
if (tableBookmark != null)
{
var tableRange = tableBookmark.Range;
// 創建表格(標題行+數據行)
var table = document.Tables.Add(tableRange, data.Count + 1, 5);
// 設置表頭
table.Cell(1, 1).Range.Text = "部門";
table.Cell(1, 2).Range.Text = "收入";
table.Cell(1, 3).Range.Text = "支出";
table.Cell(1, 4).Range.Text = "利潤";
table.Cell(1, 5).Range.Text = "增長率";
// 填充數據
for (int i = 0; i < data.Count; i++)
{
var item = data[i];
table.Cell(i + 2, 1).Range.Text = item.Department;
table.Cell(i + 2, 2).Range.Text = item.Revenue.ToString("C");
table.Cell(i + 2, 3).Range.Text = item.Expenses.ToString("C");
table.Cell(i + 2, 4).Range.Text = item.Profit.ToString("C");
table.Cell(i + 2, 5).Range.Text = $"{item.GrowthRate:P2}";
}
// 格式化表格
table.Borders.Enable = 1;
for (int i = 1; i <= table.Rows.Count; i++)
{
for (int j = 1; j <= table.Columns.Count; j++)
{
table.Cell(i, j).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
}
}
}
// 保存報告
string outputPath = $@"C:\Reports\FinancialReport_{reportMonth:yyyyMM}.docx";
document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
document.Close();
Console.WriteLine($"財務報告已生成: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"生成財務報告時發生錯誤: {ex.Message}");
}
}
}
使用 Selection 對象
Selection對象代表文檔中當前選中的區域。通過Selection對象,我們可以像在Word界面中操作一樣插入文本。
// 獲取當前選擇區域
var selection = document.Selection;
// 插入文本
selection.InsertText("這是通過Selection對象插入的文本。");
// 插入段落
selection.InsertParagraph();
// 插入換行符
selection.InsertLineBreak();
雖然Selection對象使用起來很直觀,但在自動化處理中,我們通常不推薦將其作為主要方式,因為它依賴于當前光標位置,可能導致不可預期的結果。
應用場景:交互式文檔編輯器
在某些場景中,可能需要開發一個交互式文檔編輯器,允許用戶通過界面操作文檔。
// 交互式文檔編輯器
public class InteractiveDocumentEditor
{
private IWordApplication _wordApp;
private IWordDocument _document;
/// <summary>
/// 初始化編輯器
/// </summary>
public void InitializeEditor()
{
try
{
// 創建可見的Word應用程序實例
_wordApp = WordFactory.BlankWorkbook();
_wordApp.Visibility = WordAppVisibility.Visible;
_document = _wordApp.ActiveDocument;
// 顯示歡迎信息
var selection = _document.Selection;
selection.Font.Name = "微軟雅黑";
selection.Font.Size = 14;
selection.Font.Bold = true;
selection.Text = "歡迎使用交互式文檔編輯器\n\n";
selection.Font.Bold = false;
selection.Font.Size = 12;
selection.Text = "請開始編輯您的文檔...\n";
}
catch (Exception ex)
{
Console.WriteLine($"初始化編輯器時發生錯誤: {ex.Message}");
}
}
/// <summary>
/// 在光標位置插入文本
/// </summary>
/// <param name="text">要插入的文本</param>
public void InsertTextAtCursor(string text)
{
try
{
if (_document != null)
{
var selection = _document.Selection;
selection.InsertText(text);
}
}
catch (Exception ex)
{
Console.WriteLine($"插入文本時發生錯誤: {ex.Message}");
}
}
/// <summary>
/// 在光標位置插入日期
/// </summary>
public void InsertCurrentDate()
{
try
{
if (_document != null)
{
var selection = _document.Selection;
selection.InsertText(DateTime.Now.ToString("yyyy年MM月dd日"));
}
}
catch (Exception ex)
{
Console.WriteLine($"插入日期時發生錯誤: {ex.Message}");
}
}
/// <summary>
/// 清理資源
/// </summary>
public void Cleanup()
{
try
{
_document?.Close(false); // 不保存更改
_wordApp?.Quit();
}
catch (Exception ex)
{
Console.WriteLine($"清理資源時發生錯誤: {ex.Message}");
}
}
}
使用 Document.Content 和 Document.Paragraphs 等集合
通過文檔的集合屬性,我們可以更結構化地操作文檔內容。
// 使用Document.Content獲取整個文檔內容
var contentRange = document.Content;
contentRange.Text += "添加到文檔末尾的內容。\n";
// 使用Paragraphs集合添加新段落
var newParagraph = document.Paragraphs.Add();
newParagraph.Range.Text = "這是一個新段落。";
這種方式適合于需要按結構化方式處理文檔內容的場景。
應用場景:批量文檔處理
在企業環境中,經常需要批量處理大量文檔,例如為多份合同添加相同的條款。
// 批量文檔處理器
public class BatchDocumentProcessor
{
/// <summary>
/// 為多個文檔添加通用條款
/// </summary>
/// <param name="documentPaths">文檔路徑列表</param>
/// <param name="termsText">通用條款文本</param>
public void AddTermsToDocuments(List<string> documentPaths, string termsText)
{
foreach (var documentPath in documentPaths)
{
try
{
// 打開文檔
using var wordApp = WordFactory.Open(documentPath);
var document = wordApp.ActiveDocument;
// 隱藏Word應用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 在文檔末尾添加通用條款
var contentRange = document.Content;
contentRange.Collapse(WdCollapseDirection.wdCollapseEnd);
// 添加分頁符
contentRange.InsertBreak(WdBreakType.wdPageBreak);
// 添加條款標題
contentRange.Text += "\n通用條款\n\n";
contentRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
contentRange.Font.Bold = true;
contentRange.Font.Size = 14;
// 重置格式
contentRange.Collapse(WdCollapseDirection.wdCollapseEnd);
contentRange.Font.Bold = false;
contentRange.Font.Size = 12;
contentRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
// 添加條款內容
contentRange.Text += termsText;
// 保存文檔
document.Save();
document.Close();
Console.WriteLine($"已為文檔添加通用條款: {documentPath}");
}
catch (Exception ex)
{
Console.WriteLine($"處理文檔 {documentPath} 時發生錯誤: {ex.Message}");
}
}
}
/// <summary>
/// 為多個文檔添加頁眉和頁腳
/// </summary>
/// <param name="documentPaths">文檔路徑列表</param>
/// <param name="headerText">頁眉文本</param>
/// <param name="footerText">頁腳文本</param>
public void AddHeaderFooterToDocuments(List<string> documentPaths, string headerText, string footerText)
{
foreach (var documentPath in documentPaths)
{
try
{
// 打開文檔
using var wordApp = WordFactory.Open(documentPath);
var document = wordApp.ActiveDocument;
// 隱藏Word應用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 設置頁眉
foreach (Section section in document.Sections)
{
var headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
headerRange.Text = headerText;
headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
}
// 設置頁腳
foreach (Section section in document.Sections)
{
var footerRange = section.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
footerRange.Text = footerText;
footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
}
// 保存文檔
document.Save();
document.Close();
Console.WriteLine($"已為文檔添加頁眉頁腳: {documentPath}");
}
catch (Exception ex)
{
Console.WriteLine($"處理文檔 {documentPath} 時發生錯誤: {ex.Message}");
}
}
}
}
3.2 字體格式設置 (Font Object)
在文檔處理中,字體格式設置是提升文檔可讀性和美觀度的重要手段。MudTools.OfficeInterop.Word通過IWordFont接口提供了豐富的字體格式設置功能。
基本字體屬性設置
IWordFont接口提供了設置字體名稱、大小、顏色、加粗、斜體、下劃線等基本屬性的方法。
// 獲取文檔內容范圍
var range = document.Content;
// 設置字體名稱
range.Font.Name = "微軟雅黑";
// 設置字體大小(單位:磅)
range.Font.Size = 12;
// 設置字體顏色
range.Font.Color = WdColor.wdColorBlue;
// 設置加粗
range.Font.Bold = true;
// 設置斜體
range.Font.Italic = true;
// 設置下劃線
range.Font.Underline = true;
高級字體屬性設置
除了基本屬性外,IWordFont還支持更多高級屬性設置:
// 設置上標
range.Font.Superscript = true;
// 設置下標
range.Font.Subscript = true;
// 設置字符間距
range.Font.Spacing = 2; // 增加2磅間距
// 設置字符縮放比例
range.Font.Scaling = 150; // 150%大小
// 設置字符位置偏移
range.Font.Position = 3; // 上移3磅
應用場景:科學文檔格式化
在學術或科研環境中,經常需要處理包含數學公式、化學方程式等特殊格式的文檔。
// 科學文檔格式化器
public class ScientificDocumentFormatter
{
/// <summary>
/// 格式化化學方程式
/// </summary>
/// <param name="document">Word文檔</param>
public void FormatChemicalEquations(IWordDocument document)
{
try
{
// 查找所有化學方程式(假設用[chem]標記)
var range = document.Content.Duplicate;
while (range.FindAndReplace("[chem]", "", WdReplace.wdReplaceNone))
{
// 獲取方程式內容
var equationRange = document.Range(range.Start, range.End);
// 格式化為下標
equationRange.Font.Subscript = true;
equationRange.Font.Size = 10;
equationRange.Font.Name = "Cambria Math";
}
}
catch (Exception ex)
{
Console.WriteLine($"格式化化學方程式時發生錯誤: {ex.Message}");
}
}
/// <summary>
/// 格式化數學公式
/// </summary>
/// <param name="document">Word文檔</param>
public void FormatMathematicalFormulas(IWordDocument document)
{
try
{
// 查找所有數學公式(假設用[math]標記)
var range = document.Content.Duplicate;
while (range.FindAndReplace("[math]", "", WdReplace.wdReplaceNone))
{
// 獲取公式內容
var formulaRange = document.Range(range.Start, range.End);
// 設置字體為數學字體
formulaRange.Font.Name = "Cambria Math";
formulaRange.Font.Size = 12;
// 處理上標(用^標記)
var superscriptRange = formulaRange.Duplicate;
while (superscriptRange.FindAndReplace("^", "", WdReplace.wdReplaceNone))
{
var supRange = document.Range(superscriptRange.Start, superscriptRange.End + 1);
supRange.Font.Superscript = true;
supRange.Font.Size = 8;
}
// 處理下標(用_標記)
var subscriptRange = formulaRange.Duplicate;
while (subscriptRange.FindAndReplace("_", "", WdReplace.wdReplaceNone))
{
var subRange = document.Range(subscriptRange.Start, subscriptRange.End + 1);
subRange.Font.Subscript = true;
subRange.Font.Size = 8;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"格式化數學公式時發生錯誤: {ex.Message}");
}
}
/// <summary>
/// 格式化代碼片段
/// </summary>
/// <param name="document">Word文檔</param>
public void FormatCodeSnippets(IWordDocument document)
{
try
{
// 查找所有代碼片段(假設用[code]標記)
var range = document.Content.Duplicate;
while (range.FindAndReplace("[code]", "", WdReplace.wdReplaceNone))
{
// 獲取代碼內容
var codeRange = document.Range(range.Start, range.End);
// 設置等寬字體
codeRange.Font.Name = "Consolas";
codeRange.Font.Size = 10;
codeRange.Font.Bold = false;
// 設置背景色
codeRange.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
// 添加邊框
codeRange.Borders.Enable = 1;
}
}
catch (Exception ex)
{
Console.WriteLine($"格式化代碼片段時發生錯誤: {ex.Message}");
}
}
}
3.3 段落格式設置 (ParagraphFormat Object)
段落格式決定了文本的布局和視覺效果。通過IWordParagraphFormat接口,我們可以設置段落的對齊方式、縮進、行距等屬性。
段落對齊方式
// 獲取文檔內容范圍
var range = document.Content;
// 設置段落對齊方式
range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; // 居中對齊
// 其他選項包括:
// WdParagraphAlignment.wdAlignParagraphLeft - 左對齊
// WdParagraphAlignment.wdAlignParagraphRight - 右對齊
// WdParagraphAlignment.wdAlignParagraphJustify - 兩端對齊
縮進設置
// 設置首行縮進(單位:磅)
range.ParagraphFormat.FirstLineIndent = 21; // 約等于2個字符寬度
// 設置左縮進
range.ParagraphFormat.LeftIndent = 36; // 約等于3個字符寬度
// 設置右縮進
range.ParagraphFormat.RightIndent = 18; // 約等于1.5個字符寬度
行距和間距設置
// 設置行距規則
range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceDouble; // 雙倍行距
// 其他選項包括:
// WdLineSpacing.wdLineSpaceSingle - 單倍行距
// WdLineSpacing.wdLineSpace1pt5 - 1.5倍行距
// WdLineSpacing.wdLineSpaceExactly - 固定值行距
// WdLineSpacing.wdLineSpaceMultiple - 多倍行距
// 設置段前間距(單位:磅)
range.ParagraphFormat.SpaceBefore = 12;
// 設置段后間距(單位:磅)
range.ParagraphFormat.SpaceAfter = 12;
應用場景:文檔樣式統一化
在企業環境中,為了保持文檔風格的一致性,經常需要對文檔進行樣式統一化處理。
// 文檔樣式統一化工具
public class DocumentStyleUnifier
{
/// <summary>
/// 統一文檔標題樣式
/// </summary>
/// <param name="document">Word文檔</param>
public void UnifyHeadingStyles(IWordDocument document)
{
try
{
// 處理一級標題(以#開頭的段落)
var heading1Range = document.Content.Duplicate;
while (heading1Range.FindAndReplace("# ", "", WdReplace.wdReplaceNone))
{
// 獲取標題段落
var para = heading1Range.Paragraphs.First();
var paraRange = para.Range;
// 設置一級標題樣式
paraRange.Font.Name = "黑體";
paraRange.Font.Size = 16;
paraRange.Font.Bold = true;
paraRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
paraRange.ParagraphFormat.SpaceBefore = 18;
paraRange.ParagraphFormat.SpaceAfter = 12;
// 移除標記符號
paraRange.Text = paraRange.Text.Replace("# ", "");
}
// 處理二級標題(以##開頭的段落)
var heading2Range = document.Content.Duplicate;
while (heading2Range.FindAndReplace("## ", "", WdReplace.wdReplaceNone))
{
// 獲取標題段落
var para = heading2Range.Paragraphs.First();
var paraRange = para.Range;
// 設置二級標題樣式
paraRange.Font.Name = "微軟雅黑";
paraRange.Font.Size = 14;
paraRange.Font.Bold = true;
paraRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
paraRange.ParagraphFormat.SpaceBefore = 12;
paraRange.ParagraphFormat.SpaceAfter = 6;
// 移除標記符號
paraRange.Text = paraRange.Text.Replace("## ", "");
}
}
catch (Exception ex)
{
Console.WriteLine($"統一標題樣式時發生錯誤: {ex.Message}");
}
}
/// <summary>
/// 統一文檔正文樣式
/// </summary>
/// <param name="document">Word文檔</param>
public void UnifyBodyTextStyles(IWordDocument document)
{
try
{
// 獲取文檔正文范圍
var bodyRange = document.Content;
// 設置正文樣式
bodyRange.Font.Name = "仿宋_GB2312";
bodyRange.Font.Size = 12;
bodyRange.ParagraphFormat.FirstLineIndent = 28; // 首行縮進2字符
bodyRange.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpace1pt5; // 1.5倍行距
bodyRange.ParagraphFormat.SpaceBefore = 0;
bodyRange.ParagraphFormat.SpaceAfter = 0;
}
catch (Exception ex)
{
Console.WriteLine($"統一正文樣式時發生錯誤: {ex.Message}");
}
}
/// <summary>
/// 統一列表樣式
/// </summary>
/// <param name="document">Word文檔</param>
public void UnifyListStyles(IWordDocument document)
{
try
{
// 處理無序列表(以-開頭的行)
var bulletRange = document.Content.Duplicate;
while (bulletRange.FindAndReplace("- ", "", WdReplace.wdReplaceNone))
{
var listRange = document.Range(bulletRange.Start, bulletRange.End);
// 應用項目符號列表格式
listRange.ListFormat.ApplyBulletDefault();
// 設置列表項格式
listRange.ParagraphFormat.LeftIndent = 36;
listRange.ParagraphFormat.FirstLineIndent = -18;
}
// 處理有序列表(以數字.開頭的行)
for (int i = 1; i <= 9; i++)
{
var numberedRange = document.Content.Duplicate;
while (numberedRange.FindAndReplace($"{i}. ", "", WdReplace.wdReplaceNone))
{
var listRange = document.Range(numberedRange.Start, numberedRange.End);
// 應用編號列表格式
listRange.ListFormat.ApplyNumberDefault();
// 設置列表項格式
listRange.ParagraphFormat.LeftIndent = 36;
listRange.ParagraphFormat.FirstLineIndent = -18;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"統一列表樣式時發生錯誤: {ex.Message}");
}
}
}
3.4 實戰:創建一個格式規范的商業信函模板
現在,讓我們綜合運用前面學到的知識,創建一個格式規范的商業信函模板。
using MudTools.OfficeInterop;
using MudTools.OfficeInterop.Word;
using System;
public class BusinessLetterTemplate
{
public void CreateBusinessLetter()
{
try
{
// 創建一個新的空白文檔
using var wordApp = WordFactory.BlankWorkbook();
var document = wordApp.ActiveDocument;
// 隱藏Word應用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
// 禁止顯示警告
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 設置文檔整體字體
document.Content.Font.Name = "仿宋_GB2312";
document.Content.Font.Size = 12;
// 插入發信人信息(右對齊)
var senderRange = document.Range(0, 0);
senderRange.Text = "發信人公司名稱\n地址\n電話:XXX-XXXXXXX\n郵箱:xxxx@xxxx.com\n\n";
senderRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
// 插入日期(右對齊)
var dateRange = document.Range(document.Content.End - 1, document.Content.End - 1);
dateRange.Text = DateTime.Now.ToString("yyyy年MM月dd日") + "\n\n";
dateRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
// 插入收信人信息(左對齊)
var recipientRange = document.Range(document.Content.End - 1, document.Content.End - 1);
recipientRange.Text = "收信人姓名\n收信人職位\n收信人公司名稱\n收信人地址\n\n";
recipientRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
// 插入信件正文標題(居中,加粗)
var titleRange = document.Range(document.Content.End - 1, document.Content.End - 1);
titleRange.Text = "商務合作邀請函\n\n";
titleRange.Font.Bold = true;
titleRange.Font.Size = 16;
titleRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
// 重置字體大小
titleRange.Font.Size = 12;
// 插入正文內容(首行縮進)
var contentRange = document.Range(document.Content.End - 1, document.Content.End - 1);
string content = "尊敬的合作伙伴:\n\n" +
" 首先感謝您一直以來對我們公司的關注與支持。我們誠摯地邀請您參與我們的新項目合作。" +
"該項目旨在通過雙方的優勢資源整合,實現互利共贏的目標。\n\n" +
" 我們相信,通過雙方的精誠合作,必將開創更加美好的未來。期待您的積極回應," +
"并希望能盡快與您展開深入的交流與探討。\n\n" +
" 如有任何疑問,請隨時與我們聯系。\n\n" +
"此致\n敬禮!\n\n\n";
contentRange.Text = content;
// 設置正文段落格式(首行縮進2字符)
contentRange.ParagraphFormat.FirstLineIndent = 28; // 約等于2個字符寬度
// 插入發信人簽名
var signatureRange = document.Range(document.Content.End - 1, document.Content.End - 1);
signatureRange.Text = "發信人姓名\n發信人職位\n發信人公司名稱";
signatureRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
// 保存文檔
string outputPath = @"C:\Temp\BusinessLetterTemplate.docx";
document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
Console.WriteLine($"商業信函模板已創建: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"創建商業信函模板時發生錯誤: {ex.Message}");
}
}
public void CreateFormattedBusinessLetter(string senderCompany, string senderAddress,
string senderPhone, string senderEmail,
string recipientName, string recipientTitle,
string recipientCompany, string recipientAddress,
string letterSubject, string letterContent)
{
try
{
// 基于模板創建文檔
using var wordApp = WordFactory.BlankWorkbook();
var document = wordApp.ActiveDocument;
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 設置文檔整體字體
document.Content.Font.Name = "仿宋_GB2312";
document.Content.Font.Size = 12;
// 插入發信人信息
var senderRange = document.Range(0, 0);
senderRange.Text = $"{senderCompany}\n{senderAddress}\n電話:{senderPhone}\n郵箱:{senderEmail}\n\n";
senderRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
// 插入日期
var dateRange = document.Range(document.Content.End - 1, document.Content.End - 1);
dateRange.Text = DateTime.Now.ToString("yyyy年MM月dd日") + "\n\n";
dateRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
// 插入收信人信息
var recipientRange = document.Range(document.Content.End - 1, document.Content.End - 1);
recipientRange.Text = $"{recipientName}\n{recipientTitle}\n{recipientCompany}\n{recipientAddress}\n\n";
recipientRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
// 插入信件標題
var titleRange = document.Range(document.Content.End - 1, document.Content.End - 1);
titleRange.Text = $"{letterSubject}\n\n";
titleRange.Font.Bold = true;
titleRange.Font.Size = 16;
titleRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
titleRange.Font.Size = 12;
// 插入正文內容
var contentRange = document.Range(document.Content.End - 1, document.Content.End - 1);
contentRange.Text = letterContent;
contentRange.ParagraphFormat.FirstLineIndent = 28;
// 插入發信人簽名占位符
var signatureRange = document.Range(document.Content.End - 1, document.Content.End - 1);
signatureRange.Text = "\n\n發信人簽名:___________\n發信人姓名\n發信人職位\n發信人公司名稱";
signatureRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
// 保存文檔
string outputPath = $@"C:\Temp\{letterSubject}.docx";
document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
Console.WriteLine($"格式化的商業信函已創建: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"創建格式化的商業信函時發生錯誤: {ex.Message}");
}
}
}
應用場景:企業文檔自動化系統
基于我們學到的知識,可以構建一個完整的企業文檔自動化系統:
// 企業文檔自動化系統
public class EnterpriseDocumentAutomationSystem
{
/// <summary>
/// 商務信函生成服務
/// </summary>
public class BusinessLetterService
{
/// <summary>
/// 生成商務信函
/// </summary>
/// <param name="request">信函請求參數</param>
/// <returns>生成的文檔路徑</returns>
public string GenerateBusinessLetter(BusinessLetterRequest request)
{
try
{
using var wordApp = WordFactory.BlankWorkbook();
var document = wordApp.ActiveDocument;
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 應用標準模板樣式
ApplyStandardStyles(document);
// 填充信函內容
FillLetterContent(document, request);
// 保存文檔
string outputPath = $@"C:\Documents\BusinessLetters\{request.LetterId}.docx";
document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
document.Close();
return outputPath;
}
catch (Exception ex)
{
throw new DocumentGenerationException($"生成商務信函時發生錯誤: {ex.Message}", ex);
}
}
private void ApplyStandardStyles(IWordDocument document)
{
// 設置全局字體
document.Content.Font.Name = "仿宋_GB2312";
document.Content.Font.Size = 12;
// 設置頁面邊距
document.PageSetup.TopMargin = 72; // 1英寸
document.PageSetup.BottomMargin = 72; // 1英寸
document.PageSetup.LeftMargin = 90; // 1.25英寸
document.PageSetup.RightMargin = 90; // 1.25英寸
}
private void FillLetterContent(IWordDocument document, BusinessLetterRequest request)
{
// 插入發信人信息
InsertSenderInfo(document, request.SenderInfo);
// 插入日期
InsertDate(document, request.LetterDate);
// 插入收信人信息
InsertRecipientInfo(document, request.RecipientInfo);
// 插入信函標題
InsertLetterTitle(document, request.Subject);
// 插入正文內容
InsertLetterContent(document, request.Content);
// 插入簽名
InsertSignature(document, request.SenderInfo);
}
private void InsertSenderInfo(IWordDocument document, SenderInfo senderInfo)
{
var range = document.Range(0, 0);
range.Text = $"{senderInfo.Company}\n{senderInfo.Address}\n電話:{senderInfo.Phone}\n郵箱:{senderInfo.Email}\n\n";
range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
}
private void InsertDate(IWordDocument document, DateTime date)
{
var range = document.Range(document.Content.End - 1, document.Content.End - 1);
range.Text = date.ToString("yyyy年MM月dd日") + "\n\n";
range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
}
private void InsertRecipientInfo(IWordDocument document, RecipientInfo recipientInfo)
{
var range = document.Range(document.Content.End - 1, document.Content.End - 1);
range.Text = $"{recipientInfo.Name}\n{recipientInfo.Title}\n{recipientInfo.Company}\n{recipientInfo.Address}\n\n";
range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
}
private void InsertLetterTitle(IWordDocument document, string subject)
{
var range = document.Range(document.Content.End - 1, document.Content.End - 1);
range.Text = $"{subject}\n\n";
range.Font.Bold = true;
range.Font.Size = 16;
range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
range.Font.Size = 12;
}
private void InsertLetterContent(IWordDocument document, string content)
{
var range = document.Range(document.Content.End - 1, document.Content.End - 1);
range.Text = content;
range.ParagraphFormat.FirstLineIndent = 28;
}
private void InsertSignature(IWordDocument document, SenderInfo senderInfo)
{
var range = document.Range(document.Content.End - 1, document.Content.End - 1);
range.Text = $"\n\n發信人簽名:___________\n{senderInfo.Name}\n{senderInfo.Title}\n{senderInfo.Company}";
range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
}
}
// 數據模型類
public class BusinessLetterRequest
{
public string LetterId { get; set; }
public SenderInfo SenderInfo { get; set; }
public RecipientInfo RecipientInfo { get; set; }
public DateTime LetterDate { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
}
public class SenderInfo
{
public string Company { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
public class RecipientInfo
{
public string Name { get; set; }
public string Title { get; set; }
public string Company { get; set; }
public string Address { get; set; }
}
public class DocumentGenerationException : Exception
{
public DocumentGenerationException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
小結
本文詳細介紹了使用MudTools.OfficeInterop.Word庫操作Word文檔文本和格式的方法:
- 文本插入方式:介紹了通過Range.Text屬性、Selection對象和文檔集合屬性等多種方式插入文本,并提供了相應的應用場景和代碼示例
- 字體格式設置:演示了如何使用IWordFont接口設置字體名稱、大小、顏色、加粗、斜體等屬性,并展示了在科學文檔格式化中的應用
- 段落格式設置:展示了如何使用IWordParagraphFormat接口設置段落對齊方式、縮進、行距等屬性,并提供了文檔樣式統一化的實際應用
- 實戰應用:通過創建商業信函模板和企業文檔自動化系統,綜合運用了所學的文本和格式操作知識
掌握這些文本和格式操作技巧,可以幫助我們創建更加專業和美觀的Word文檔,為后續的文檔自動化處理奠定堅實基礎。
在下一篇文章中,我們將探討更高級的主題,包括表格操作、圖片插入和文檔樣式設置等內容。敬請期待!

浙公網安備 33010602011771號