.NET實(shí)現(xiàn)Word文本插入與格式設(shè)置的方法指南
在前面的文章中,我們已經(jīng)了解了Word對象模型的核心組件,包括Application、Document和Range對象。掌握了這些基礎(chǔ)知識(shí)后,我們現(xiàn)在可以進(jìn)一步深入到文檔內(nèi)容的處理,特別是文本的插入和格式化操作。
本文將詳細(xì)介紹如何使用MudTools.OfficeInterop.Word庫來操作Word文檔中的文本內(nèi)容,包括多種插入文本的方法、字體格式設(shè)置和段落格式設(shè)置。最后,我們將通過一個(gè)實(shí)戰(zhàn)示例,創(chuàng)建一個(gè)格式規(guī)范的商業(yè)信函模板,來綜合運(yùn)用所學(xué)知識(shí)。
插入文本的多種方式
在Word文檔自動(dòng)化處理中,插入文本是最基本也是最重要的操作之一。MudTools.OfficeInterop.Word提供了多種方式來插入文本,每種方式都有其適用場景。
使用 Range.Text 屬性
Range對象是Word對象模型中最核心的組件之一,它代表文檔中的一個(gè)連續(xù)區(qū)域。通過設(shè)置Range.Text屬性,我們可以輕松地在指定位置插入或替換文本。
// 獲取文檔的整個(gè)內(nèi)容范圍 var range = document.Content; // 在文檔末尾插入文本 range.Collapse(WdCollapseDirection.wdCollapseEnd); range.Text = "這是通過Range.Text屬性插入的文本。\n"; // 替換文檔中的所有內(nèi)容 range.Text = "這是替換后的全新內(nèi)容。";
Range.Text屬性是最直接的文本操作方式,適合于需要精確控制文本位置的場景。
應(yīng)用場景:動(dòng)態(tài)報(bào)告生成
在企業(yè)環(huán)境中,經(jīng)常需要根據(jù)數(shù)據(jù)動(dòng)態(tài)生成報(bào)告。例如,財(cái)務(wù)部門需要每月生成財(cái)務(wù)報(bào)告,其中包含關(guān)鍵指標(biāo)數(shù)據(jù)。
using MudTools.OfficeInterop;
using MudTools.OfficeInterop.Word;
using System;
using System.Collections.Generic;
// 財(cái)務(wù)數(shù)據(jù)模型
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; }
}
// 財(cái)務(wù)報(bào)告生成器
public class FinancialReportGenerator
{
/// <summary>
/// 生成財(cái)務(wù)報(bào)告
/// </summary>
/// <param name="data">財(cái)務(wù)數(shù)據(jù)列表</param>
/// <param name="reportMonth">報(bào)告月份</param>
public void GenerateFinancialReport(List<FinancialData> data, DateTime reportMonth)
{
try
{
// 使用模板創(chuàng)建報(bào)告文檔
using var wordApp = WordFactory.CreateFrom(@"C:\Templates\FinancialReportTemplate.dotx");
var document = wordApp.ActiveDocument;
// 隱藏Word應(yīng)用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 替換報(bào)告標(biāo)題中的月份信息
document.FindAndReplace("[MONTH]", reportMonth.ToString("yyyy年MM月"));
// 定位到數(shù)據(jù)表格位置
var tableBookmark = document.Bookmarks["FinancialDataTable"];
if (tableBookmark != null)
{
var tableRange = tableBookmark.Range;
// 創(chuàng)建表格(標(biāo)題行+數(shù)據(jù)行)
var table = document.Tables.Add(tableRange, data.Count + 1, 5);
// 設(shè)置表頭
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 = "增長率";
// 填充數(shù)據(jù)
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;
}
}
}
// 保存報(bào)告
string outputPath = $@"C:\Reports\FinancialReport_{reportMonth:yyyyMM}.docx";
document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
document.Close();
Console.WriteLine($"財(cái)務(wù)報(bào)告已生成: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"生成財(cái)務(wù)報(bào)告時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
}
使用 Selection 對象
Selection對象代表文檔中當(dāng)前選中的區(qū)域。通過Selection對象,我們可以像在Word界面中操作一樣插入文本。
// 獲取當(dāng)前選擇區(qū)域
var selection = document.Selection;
// 插入文本
selection.InsertText("這是通過Selection對象插入的文本。");
// 插入段落
selection.InsertParagraph();
// 插入換行符
selection.InsertLineBreak();
雖然Selection對象使用起來很直觀,但在自動(dòng)化處理中,我們通常不推薦將其作為主要方式,因?yàn)樗蕾囉诋?dāng)前光標(biāo)位置,可能導(dǎo)致不可預(yù)期的結(jié)果。
應(yīng)用場景:交互式文檔編輯器
在某些場景中,可能需要開發(fā)一個(gè)交互式文檔編輯器,允許用戶通過界面操作文檔。
// 交互式文檔編輯器
public class InteractiveDocumentEditor
{
private IWordApplication _wordApp;
private IWordDocument _document;
/// <summary>
/// 初始化編輯器
/// </summary>
public void InitializeEditor()
{
try
{
// 創(chuàng)建可見的Word應(yīng)用程序?qū)嵗?
_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($"初始化編輯器時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
/// <summary>
/// 在光標(biāo)位置插入文本
/// </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($"插入文本時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
/// <summary>
/// 在光標(biāo)位置插入日期
/// </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($"插入日期時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
/// <summary>
/// 清理資源
/// </summary>
public void Cleanup()
{
try
{
_document?.Close(false); // 不保存更改
_wordApp?.Quit();
}
catch (Exception ex)
{
Console.WriteLine($"清理資源時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
}
使用 Document.Content 和 Document.Paragraphs 等集合
通過文檔的集合屬性,我們可以更結(jié)構(gòu)化地操作文檔內(nèi)容。
// 使用Document.Content獲取整個(gè)文檔內(nèi)容 var contentRange = document.Content; contentRange.Text += "添加到文檔末尾的內(nèi)容。\n"; // 使用Paragraphs集合添加新段落 var newParagraph = document.Paragraphs.Add(); newParagraph.Range.Text = "這是一個(gè)新段落。";
這種方式適合于需要按結(jié)構(gòu)化方式處理文檔內(nèi)容的場景。
應(yīng)用場景:批量文檔處理
在企業(yè)環(huán)境中,經(jīng)常需要批量處理大量文檔,例如為多份合同添加相同的條款。
// 批量文檔處理器
public class BatchDocumentProcessor
{
/// <summary>
/// 為多個(gè)文檔添加通用條款
/// </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應(yīng)用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 在文檔末尾添加通用條款
var contentRange = document.Content;
contentRange.Collapse(WdCollapseDirection.wdCollapseEnd);
// 添加分頁符
contentRange.InsertBreak(WdBreakType.wdPageBreak);
// 添加條款標(biāo)題
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;
// 添加條款內(nèi)容
contentRange.Text += termsText;
// 保存文檔
document.Save();
document.Close();
Console.WriteLine($"已為文檔添加通用條款: {documentPath}");
}
catch (Exception ex)
{
Console.WriteLine($"處理文檔 {documentPath} 時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
}
/// <summary>
/// 為多個(gè)文檔添加頁眉和頁腳
/// </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應(yīng)用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 設(shè)置頁眉
foreach (Section section in document.Sections)
{
var headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
headerRange.Text = headerText;
headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
}
// 設(shè)置頁腳
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} 時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
}
}
字體格式設(shè)置 (Font Object)
在文檔處理中,字體格式設(shè)置是提升文檔可讀性和美觀度的重要手段。MudTools.OfficeInterop.Word通過IWordFont接口提供了豐富的字體格式設(shè)置功能。
基本字體屬性設(shè)置
IWordFont接口提供了設(shè)置字體名稱、大小、顏色、加粗、斜體、下劃線等基本屬性的方法。
// 獲取文檔內(nèi)容范圍 var range = document.Content; // 設(shè)置字體名稱 range.Font.Name = "微軟雅黑"; // 設(shè)置字體大小(單位:磅) range.Font.Size = 12; // 設(shè)置字體顏色 range.Font.Color = WdColor.wdColorBlue; // 設(shè)置加粗 range.Font.Bold = true; // 設(shè)置斜體 range.Font.Italic = true; // 設(shè)置下劃線 range.Font.Underline = true;
高級(jí)字體屬性設(shè)置
除了基本屬性外,IWordFont還支持更多高級(jí)屬性設(shè)置:
// 設(shè)置上標(biāo) range.Font.Superscript = true; // 設(shè)置下標(biāo) range.Font.Subscript = true; // 設(shè)置字符間距 range.Font.Spacing = 2; // 增加2磅間距 // 設(shè)置字符縮放比例 range.Font.Scaling = 150; // 150%大小 // 設(shè)置字符位置偏移 range.Font.Position = 3; // 上移3磅
應(yīng)用場景:科學(xué)文檔格式化
在學(xué)術(shù)或科研環(huán)境中,經(jīng)常需要處理包含數(shù)學(xué)公式、化學(xué)方程式等特殊格式的文檔。
// 科學(xué)文檔格式化器
public class ScientificDocumentFormatter
{
/// <summary>
/// 格式化化學(xué)方程式
/// </summary>
/// <param name="document">Word文檔</param>
public void FormatChemicalEquations(IWordDocument document)
{
try
{
// 查找所有化學(xué)方程式(假設(shè)用[chem]標(biāo)記)
var range = document.Content.Duplicate;
while (range.FindAndReplace("[chem]", "", WdReplace.wdReplaceNone))
{
// 獲取方程式內(nèi)容
var equationRange = document.Range(range.Start, range.End);
// 格式化為下標(biāo)
equationRange.Font.Subscript = true;
equationRange.Font.Size = 10;
equationRange.Font.Name = "Cambria Math";
}
}
catch (Exception ex)
{
Console.WriteLine($"格式化化學(xué)方程式時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
/// <summary>
/// 格式化數(shù)學(xué)公式
/// </summary>
/// <param name="document">Word文檔</param>
public void FormatMathematicalFormulas(IWordDocument document)
{
try
{
// 查找所有數(shù)學(xué)公式(假設(shè)用[math]標(biāo)記)
var range = document.Content.Duplicate;
while (range.FindAndReplace("[math]", "", WdReplace.wdReplaceNone))
{
// 獲取公式內(nèi)容
var formulaRange = document.Range(range.Start, range.End);
// 設(shè)置字體為數(shù)學(xué)字體
formulaRange.Font.Name = "Cambria Math";
formulaRange.Font.Size = 12;
// 處理上標(biāo)(用^標(biāo)記)
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;
}
// 處理下標(biāo)(用_標(biāo)記)
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($"格式化數(shù)學(xué)公式時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
/// <summary>
/// 格式化代碼片段
/// </summary>
/// <param name="document">Word文檔</param>
public void FormatCodeSnippets(IWordDocument document)
{
try
{
// 查找所有代碼片段(假設(shè)用[code]標(biāo)記)
var range = document.Content.Duplicate;
while (range.FindAndReplace("[code]", "", WdReplace.wdReplaceNone))
{
// 獲取代碼內(nèi)容
var codeRange = document.Range(range.Start, range.End);
// 設(shè)置等寬字體
codeRange.Font.Name = "Consolas";
codeRange.Font.Size = 10;
codeRange.Font.Bold = false;
// 設(shè)置背景色
codeRange.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
// 添加邊框
codeRange.Borders.Enable = 1;
}
}
catch (Exception ex)
{
Console.WriteLine($"格式化代碼片段時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
}
段落格式設(shè)置 (ParagraphFormat Object)
段落格式?jīng)Q定了文本的布局和視覺效果。通過IWordParagraphFormat接口,我們可以設(shè)置段落的對齊方式、縮進(jìn)、行距等屬性。
段落對齊方式
// 獲取文檔內(nèi)容范圍 var range = document.Content; // 設(shè)置段落對齊方式 range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; // 居中對齊 // 其他選項(xiàng)包括: // WdParagraphAlignment.wdAlignParagraphLeft - 左對齊 // WdParagraphAlignment.wdAlignParagraphRight - 右對齊 // WdParagraphAlignment.wdAlignParagraphJustify - 兩端對齊
縮進(jìn)設(shè)置
// 設(shè)置首行縮進(jìn)(單位:磅) range.ParagraphFormat.FirstLineIndent = 21; // 約等于2個(gè)字符寬度 // 設(shè)置左縮進(jìn) range.ParagraphFormat.LeftIndent = 36; // 約等于3個(gè)字符寬度 // 設(shè)置右縮進(jìn) range.ParagraphFormat.RightIndent = 18; // 約等于1.5個(gè)字符寬度
行距和間距設(shè)置
// 設(shè)置行距規(guī)則 range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceDouble; // 雙倍行距 // 其他選項(xiàng)包括: // WdLineSpacing.wdLineSpaceSingle - 單倍行距 // WdLineSpacing.wdLineSpace1pt5 - 1.5倍行距 // WdLineSpacing.wdLineSpaceExactly - 固定值行距 // WdLineSpacing.wdLineSpaceMultiple - 多倍行距 // 設(shè)置段前間距(單位:磅) range.ParagraphFormat.SpaceBefore = 12; // 設(shè)置段后間距(單位:磅) range.ParagraphFormat.SpaceAfter = 12;
應(yīng)用場景:文檔樣式統(tǒng)一化
在企業(yè)環(huán)境中,為了保持文檔風(fēng)格的一致性,經(jīng)常需要對文檔進(jìn)行樣式統(tǒng)一化處理。
// 文檔樣式統(tǒng)一化工具
public class DocumentStyleUnifier
{
/// <summary>
/// 統(tǒng)一文檔標(biāo)題樣式
/// </summary>
/// <param name="document">Word文檔</param>
public void UnifyHeadingStyles(IWordDocument document)
{
try
{
// 處理一級(jí)標(biāo)題(以#開頭的段落)
var heading1Range = document.Content.Duplicate;
while (heading1Range.FindAndReplace("# ", "", WdReplace.wdReplaceNone))
{
// 獲取標(biāo)題段落
var para = heading1Range.Paragraphs.First();
var paraRange = para.Range;
// 設(shè)置一級(jí)標(biāo)題樣式
paraRange.Font.Name = "黑體";
paraRange.Font.Size = 16;
paraRange.Font.Bold = true;
paraRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
paraRange.ParagraphFormat.SpaceBefore = 18;
paraRange.ParagraphFormat.SpaceAfter = 12;
// 移除標(biāo)記符號(hào)
paraRange.Text = paraRange.Text.Replace("# ", "");
}
// 處理二級(jí)標(biāo)題(以##開頭的段落)
var heading2Range = document.Content.Duplicate;
while (heading2Range.FindAndReplace("## ", "", WdReplace.wdReplaceNone))
{
// 獲取標(biāo)題段落
var para = heading2Range.Paragraphs.First();
var paraRange = para.Range;
// 設(shè)置二級(jí)標(biāo)題樣式
paraRange.Font.Name = "微軟雅黑";
paraRange.Font.Size = 14;
paraRange.Font.Bold = true;
paraRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
paraRange.ParagraphFormat.SpaceBefore = 12;
paraRange.ParagraphFormat.SpaceAfter = 6;
// 移除標(biāo)記符號(hào)
paraRange.Text = paraRange.Text.Replace("## ", "");
}
}
catch (Exception ex)
{
Console.WriteLine($"統(tǒng)一標(biāo)題樣式時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
/// <summary>
/// 統(tǒng)一文檔正文樣式
/// </summary>
/// <param name="document">Word文檔</param>
public void UnifyBodyTextStyles(IWordDocument document)
{
try
{
// 獲取文檔正文范圍
var bodyRange = document.Content;
// 設(shè)置正文樣式
bodyRange.Font.Name = "仿宋_GB2312";
bodyRange.Font.Size = 12;
bodyRange.ParagraphFormat.FirstLineIndent = 28; // 首行縮進(jìn)2字符
bodyRange.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpace1pt5; // 1.5倍行距
bodyRange.ParagraphFormat.SpaceBefore = 0;
bodyRange.ParagraphFormat.SpaceAfter = 0;
}
catch (Exception ex)
{
Console.WriteLine($"統(tǒng)一正文樣式時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
/// <summary>
/// 統(tǒng)一列表樣式
/// </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);
// 應(yīng)用項(xiàng)目符號(hào)列表格式
listRange.ListFormat.ApplyBulletDefault();
// 設(shè)置列表項(xiàng)格式
listRange.ParagraphFormat.LeftIndent = 36;
listRange.ParagraphFormat.FirstLineIndent = -18;
}
// 處理有序列表(以數(shù)字.開頭的行)
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);
// 應(yīng)用編號(hào)列表格式
listRange.ListFormat.ApplyNumberDefault();
// 設(shè)置列表項(xiàng)格式
listRange.ParagraphFormat.LeftIndent = 36;
listRange.ParagraphFormat.FirstLineIndent = -18;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"統(tǒng)一列表樣式時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
}
實(shí)戰(zhàn):創(chuàng)建一個(gè)格式規(guī)范的商業(yè)信函模板
現(xiàn)在,讓我們綜合運(yùn)用前面學(xué)到的知識(shí),創(chuàng)建一個(gè)格式規(guī)范的商業(yè)信函模板。
using MudTools.OfficeInterop;
using MudTools.OfficeInterop.Word;
using System;
public class BusinessLetterTemplate
{
public void CreateBusinessLetter()
{
try
{
// 創(chuàng)建一個(gè)新的空白文檔
using var wordApp = WordFactory.BlankWorkbook();
var document = wordApp.ActiveDocument;
// 隱藏Word應(yīng)用程序以提高性能
wordApp.Visibility = WordAppVisibility.Hidden;
// 禁止顯示警告
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 設(shè)置文檔整體字體
document.Content.Font.Name = "仿宋_GB2312";
document.Content.Font.Size = 12;
// 插入發(fā)信人信息(右對齊)
var senderRange = document.Range(0, 0);
senderRange.Text = "發(fā)信人公司名稱\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;
// 插入信件正文標(biāo)題(居中,加粗)
var titleRange = document.Range(document.Content.End - 1, document.Content.End - 1);
titleRange.Text = "商務(wù)合作邀請函\n\n";
titleRange.Font.Bold = true;
titleRange.Font.Size = 16;
titleRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
// 重置字體大小
titleRange.Font.Size = 12;
// 插入正文內(nèi)容(首行縮進(jìn))
var contentRange = document.Range(document.Content.End - 1, document.Content.End - 1);
string content = "尊敬的合作伙伴:\n\n" +
" 首先感謝您一直以來對我們公司的關(guān)注與支持。我們誠摯地邀請您參與我們的新項(xiàng)目合作。" +
"該項(xiàng)目旨在通過雙方的優(yōu)勢資源整合,實(shí)現(xiàn)互利共贏的目標(biāo)。\n\n" +
" 我們相信,通過雙方的精誠合作,必將開創(chuàng)更加美好的未來。期待您的積極回應(yīng)," +
"并希望能盡快與您展開深入的交流與探討。\n\n" +
" 如有任何疑問,請隨時(shí)與我們聯(lián)系。\n\n" +
"此致\n敬禮!\n\n\n";
contentRange.Text = content;
// 設(shè)置正文段落格式(首行縮進(jìn)2字符)
contentRange.ParagraphFormat.FirstLineIndent = 28; // 約等于2個(gè)字符寬度
// 插入發(fā)信人簽名
var signatureRange = document.Range(document.Content.End - 1, document.Content.End - 1);
signatureRange.Text = "發(fā)信人姓名\n發(fā)信人職位\n發(fā)信人公司名稱";
signatureRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
// 保存文檔
string outputPath = @"C:\Temp\BusinessLetterTemplate.docx";
document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
Console.WriteLine($"商業(yè)信函模板已創(chuàng)建: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"創(chuàng)建商業(yè)信函模板時(shí)發(fā)生錯(cuò)誤: {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
{
// 基于模板創(chuàng)建文檔
using var wordApp = WordFactory.BlankWorkbook();
var document = wordApp.ActiveDocument;
wordApp.Visibility = WordAppVisibility.Hidden;
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
// 設(shè)置文檔整體字體
document.Content.Font.Name = "仿宋_GB2312";
document.Content.Font.Size = 12;
// 插入發(fā)信人信息
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;
// 插入信件標(biāo)題
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;
// 插入正文內(nèi)容
var contentRange = document.Range(document.Content.End - 1, document.Content.End - 1);
contentRange.Text = letterContent;
contentRange.ParagraphFormat.FirstLineIndent = 28;
// 插入發(fā)信人簽名占位符
var signatureRange = document.Range(document.Content.End - 1, document.Content.End - 1);
signatureRange.Text = "\n\n發(fā)信人簽名:___________\n發(fā)信人姓名\n發(fā)信人職位\n發(fā)信人公司名稱";
signatureRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
// 保存文檔
string outputPath = $@"C:\Temp\{letterSubject}.docx";
document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
Console.WriteLine($"格式化的商業(yè)信函已創(chuàng)建: {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"創(chuàng)建格式化的商業(yè)信函時(shí)發(fā)生錯(cuò)誤: {ex.Message}");
}
}
}
應(yīng)用場景:企業(yè)文檔自動(dòng)化系統(tǒng)
基于我們學(xué)到的知識(shí),可以構(gòu)建一個(gè)完整的企業(yè)文檔自動(dòng)化系統(tǒng):
// 企業(yè)文檔自動(dòng)化系統(tǒng)
public class EnterpriseDocumentAutomationSystem
{
/// <summary>
/// 商務(wù)信函生成服務(wù)
/// </summary>
public class BusinessLetterService
{
/// <summary>
/// 生成商務(wù)信函
/// </summary>
/// <param name="request">信函請求參數(shù)</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;
// 應(yīng)用標(biāo)準(zhǔn)模板樣式
ApplyStandardStyles(document);
// 填充信函內(nèi)容
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($"生成商務(wù)信函時(shí)發(fā)生錯(cuò)誤: {ex.Message}", ex);
}
}
private void ApplyStandardStyles(IWordDocument document)
{
// 設(shè)置全局字體
document.Content.Font.Name = "仿宋_GB2312";
document.Content.Font.Size = 12;
// 設(shè)置頁面邊距
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)
{
// 插入發(fā)信人信息
InsertSenderInfo(document, request.SenderInfo);
// 插入日期
InsertDate(document, request.LetterDate);
// 插入收信人信息
InsertRecipientInfo(document, request.RecipientInfo);
// 插入信函標(biāo)題
InsertLetterTitle(document, request.Subject);
// 插入正文內(nèi)容
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發(fā)信人簽名:___________\n{senderInfo.Name}\n{senderInfo.Title}\n{senderInfo.Company}";
range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
}
}
// 數(shù)據(jù)模型類
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)
{
}
}
}
小結(jié)
本文詳細(xì)介紹了使用MudTools.OfficeInterop.Word庫操作Word文檔文本和格式的方法:
- 文本插入方式:介紹了通過Range.Text屬性、Selection對象和文檔集合屬性等多種方式插入文本,并提供了相應(yīng)的應(yīng)用場景和代碼示例
- 字體格式設(shè)置:演示了如何使用IWordFont接口設(shè)置字體名稱、大小、顏色、加粗、斜體等屬性,并展示了在科學(xué)文檔格式化中的應(yīng)用
- 段落格式設(shè)置:展示了如何使用IWordParagraphFormat接口設(shè)置段落對齊方式、縮進(jìn)、行距等屬性,并提供了文檔樣式統(tǒng)一化的實(shí)際應(yīng)用
- 實(shí)戰(zhàn)應(yīng)用:通過創(chuàng)建商業(yè)信函模板和企業(yè)文檔自動(dòng)化系統(tǒng),綜合運(yùn)用了所學(xué)的文本和格式操作知識(shí)
掌握這些文本和格式操作技巧,可以幫助我們創(chuàng)建更加專業(yè)和美觀的Word文檔,為后續(xù)的文檔自動(dòng)化處理奠定堅(jiān)實(shí)基礎(chǔ)。
到此這篇關(guān)于.NET實(shí)現(xiàn)Word文本插入與格式設(shè)置的方法指南的文章就介紹到這了,更多相關(guān).NET Word文本與格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用VS2022在ASP.NET?Core中構(gòu)建輕量級(jí)服務(wù)
本文詳細(xì)講解了使用VS2022在ASP.NET?Core中構(gòu)建輕量級(jí)服務(wù)的方法,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12
.NET Core使用FluentEmail發(fā)送郵件的示例代碼
這篇文章主要介紹了.NET Core使用FluentEmail發(fā)送郵件的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
.net?core?api接口JWT方式認(rèn)證Token
本文詳細(xì)講解了.net?core?api接口JWT方式認(rèn)證Token,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12
asp.net(c#)開發(fā)中的文件上傳組件uploadify的使用方法(帶進(jìn)度條)
在asp.net開發(fā)中,有很多可以上傳的組件模塊,利用HTML的File控件(uploadify)的上傳也是一種辦法,這里為大家介紹一下(uploadify)的一些使用方法2012-12-12
IIS處理Asp.net請求和Asp.net頁面生命周期詳細(xì)說明
ASP.NET 頁運(yùn)行時(shí),此頁將經(jīng)歷一個(gè)生命周期,在生命周期中將執(zhí)行一系列處理步驟。這些步驟包括初始化、實(shí)例化控件、還原和維護(hù)狀態(tài)、運(yùn)行事件處理程序代碼以及進(jìn)行呈現(xiàn)2012-01-01

