使用Spire.Doc在C#中創(chuàng)建、寫入和讀取Word文檔的實現(xiàn)方法
引言
在日常開發(fā)中,動態(tài)生成報告、合同等Word文檔是常見需求。使用Spire.Doc for .NET,無需依賴Office組件,即可通過C#代碼高效完成文檔的創(chuàng)建、內(nèi)容寫入和數(shù)據(jù)讀取,輕松實現(xiàn)自動化文檔處理。本文將分享具體實現(xiàn)方法。
1. Spire.Doc 簡介與環(huán)境配置
Spire.Doc 是一款專業(yè)的 .NET Word 組件,專為在 .NET 應用程序中快速、高質(zhì)量地處理 Word 文檔而設計。
- 無需 Office:完全獨立的組件,不依賴 Microsoft Office。
- 功能強大:支持創(chuàng)建、編輯、轉換 Word 文檔,涵蓋文本、圖片、表格、圖表、郵件合并、書簽、表單域等幾乎所有 Word 元素。
- 高性能:優(yōu)化了文檔處理算法,在大文檔和批量處理場景下表現(xiàn)出色。
- 跨平臺:支持 .NET Framework、.NET Core、.NET 5/6/7 等多種 .NET 平臺,可在 Windows、Linux、macOS 等系統(tǒng)上運行。
- 多種格式支持:支持 DOC、DOCX、RTF、XML、TXT、HTML、ODT、OTT 等多種 Word 格式。
環(huán)境配置:
使用 Spire.Doc 非常簡單,只需通過 NuGet 包管理器安裝即可。
- 在 Visual Studio 中打開你的項目。
- 右鍵點擊項目 -> “管理 NuGet 包”。
- 在“瀏覽”選項卡中搜索
Spire.Doc。 - 點擊“安裝”按鈕,等待安裝完成。
安裝完成后,在 C# 代碼中引入必要的命名空間:
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; // 用于顏色和圖片 using System.IO; // 用于文件操作
2. 創(chuàng)建與寫入 Word 文檔
現(xiàn)在,讓我們通過具體的代碼示例,學習如何使用 Spire.Doc 創(chuàng)建并向 Word 文檔中寫入內(nèi)容。
創(chuàng)建新的 Word 文檔
實例化 Document 對象即可創(chuàng)建一個空白的 Word 文檔:
// 創(chuàng)建一個新的 Word 文檔 Document document = new Document(); // 添加一個節(jié) (Section),所有內(nèi)容都必須添加到節(jié)中 Section section = document.AddSection();
添加段落與文本
Word 文檔由段落組成,每個段落可以包含文本、圖片等元素。
// 添加一個段落
Paragraph paragraph1 = section.AddParagraph();
// 向段落中添加文本
TextRange textRange1 = paragraph1.AppendText("這是使用 Spire.Doc 創(chuàng)建的第一個段落。");
// 設置文本格式
textRange1.CharacterFormat.FontName = "微軟雅黑";
textRange1.CharacterFormat.FontSize = 14;
textRange1.CharacterFormat.TextColor = Color.DarkBlue;
textRange1.CharacterFormat.Bold = true;
// 添加另一個段落,并設置右對齊
Paragraph paragraph2 = section.AddParagraph();
paragraph2.AppendText("這是一個右對齊的段落。");
paragraph2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
插入圖片與表格
Spire.Doc 同樣支持插入圖片和創(chuàng)建表格。
插入圖片:
// 添加一個段落用于插入圖片
Paragraph imageParagraph = section.AddParagraph();
// 插入本地圖片
DocPicture picture = imageParagraph.AppendPicture(Image.FromFile("your_image.png"));
// 設置圖片大小 (可選)
picture.Width = 150;
picture.Height = 100;
創(chuàng)建與填充表格:
| API 方法 | 描述 |
|---|---|
| section.AddTable() | 在節(jié)中添加一個表格 |
| table.AddRow() | 向表格中添加行 |
| row.Cells[index] | 獲取指定索引的單元格 |
| cell.AddParagraph() | 向單元格中添加段落 |
| paragraph.AppendText() | 向段落中添加文本 |
// 添加一個表格
Table table = section.AddTable();
// 設置表格的列數(shù)和默認行高
table.ResetCells(3, 3); // 3行3列
table.DefaultRowHeight = 25;
table.TableFormat.Borders.BorderType = BorderStyle.Single; // 設置邊框
// 填充表格內(nèi)容
for (int r = 0; r < table.Rows.Count; r++)
{
TableRow row = table.Rows[r];
for (int c = 0; c < row.Cells.Count; c++)
{
TableCell cell = row.Cells[c];
// 設置單元格背景色 (可選)
if (r == 0)
{
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightGray;
}
// 添加內(nèi)容到單元格
Paragraph cellParagraph = cell.AddParagraph();
cellParagraph.AppendText($"單元格 ({r + 1}, {c + 1})");
cellParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
cellParagraph.Format.VerticalAlignment = VerticalAlignment.Middle;
}
}
保存文檔
完成內(nèi)容寫入后,將文檔保存到指定路徑:
// 保存文檔為 DOCX 格式
document.SaveToFile("MyWordDocument.docx", FileFormat.Docx);
// 也可以保存為 DOC 格式
// document.SaveToFile("MyWordDocument.doc", FileFormat.Doc);
// 關閉文檔
document.Close();
3. 讀取 Word 文檔內(nèi)容
Spire.Doc 不僅能創(chuàng)建文檔,也能輕松讀取現(xiàn)有 Word 文檔中的內(nèi)容。
加載現(xiàn)有文檔
// 加載一個已存在的 Word 文檔
Document document = new Document();
document.LoadFromFile("MyWordDocument.docx");
遍歷文檔內(nèi)容
Word 文檔的結構通常是 Document -> Section -> Body -> Paragraph/Table。我們可以通過循環(huán)遍歷來訪問各個元素。
// 遍歷文檔中的所有節(jié)
foreach (Section section in document.Sections)
{
// 遍歷節(jié)中的所有段落
foreach (DocumentObject obj in section.Body.ChildObjects)
{
if (obj.DocumentObjectType == DocumentObjectType.Paragraph)
{
Paragraph paragraph = obj as Paragraph;
Console.WriteLine($"段落文本: {paragraph.Text}");
// 遍歷段落中的所有子對象 (TextRange, Picture 等)
foreach (DocumentObject paraChild in paragraph.ChildObjects)
{
if (paraChild.DocumentObjectType == DocumentObjectType.TextRange)
{
TextRange textRange = paraChild as TextRange;
Console.WriteLine($" 文本片段: {textRange.Text}");
}
else if (paraChild.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = paraChild as DocPicture;
Console.WriteLine($" 圖片文件: {picture.ImageBytes.Length} 字節(jié)");
}
}
}
else if (obj.DocumentObjectType == DocumentObjectType.Table)
{
Table table = obj as Table;
Console.WriteLine("發(fā)現(xiàn)表格:");
// 遍歷表格的行和單元格
foreach (TableRow row in table.Rows)
{
foreach (TableCell cell in row.Cells)
{
Console.Write($" 單元格內(nèi)容: {cell.Text.Trim()} |");
}
Console.WriteLine();
}
}
}
}
提取特定信息
Spire.Doc 提供了強大的查找替換功能,可以用于提取特定文本。
// 根據(jù)關鍵字查找文本
TextSelection[] selections = document.FindAllString("Spire.Doc", true, true);
if (selections != null)
{
foreach (TextSelection selection in selections)
{
// 獲取找到的文本及其所在段落
Console.WriteLine($"找到關鍵字: '{selection.SelectedText}',位于段落: '{selection.Get As One Paragraph().Text}'");
}
}
// 讀取表格單元格內(nèi)容 (假設我們知道表格和單元格的索引)
// 假設這是文檔中的第一個表格
Table firstTable = document.Sections[0].Body.Tables[0] as Table;
if (firstTable != null && firstTable.Rows.Count > 1 && firstTable.Rows[0].Cells.Count > 0)
{
// 讀取第二行第一列的文本
string cellContent = firstTable.Rows[1].Cells[0].Text.Trim();
Console.WriteLine($"表格中的特定單元格內(nèi)容 (第二行第一列): {cellContent}");
}
4. 進階技巧與注意事項
Spire.Doc 的功能遠不止于此,它還提供了許多高級特性,可以滿足更復雜的 Word 文檔處理需求:
- 合并文檔:將多個 Word 文檔合并成一個。
- 查找替換:支持正則表達式查找和替換。
- 書簽操作:創(chuàng)建、查找和更新書簽內(nèi)容。
- 表單域:創(chuàng)建和填充 Word 表單域。
- 轉換格式:將 Word 文檔轉換為 PDF、HTML、圖片等格式。
- 文檔屬性:讀寫文檔的元數(shù)據(jù),如作者、標題等。
性能優(yōu)化:
當處理大型文檔或進行大量文檔操作時,可以考慮以下優(yōu)化:
- 批量操作:盡可能利用 Spire.Doc 提供的批量操作 API。
- 內(nèi)存管理:及時釋放不再使用的
Document對象,避免內(nèi)存泄漏。 - 文件流操作:在讀取/寫入文件時,使用
Stream可以更靈活地控制內(nèi)存。
以上就是使用Spire.Doc在C#中創(chuàng)建、寫入和讀取Word文檔的實現(xiàn)方法的詳細內(nèi)容,更多關于C# Spire.Doc創(chuàng)建、寫入和讀取Word文檔的資料請關注腳本之家其它相關文章!
相關文章
C#中使用jieba.NET、WordCloudSharp制作詞云圖的步驟
之前一篇文章介紹的是使用Python的jieba、wordcloud的庫生成詞云圖,本文則介紹在C#中如何使用jieba.NET、WordCloudSharp庫生成詞云圖,感興趣的朋友一起看看吧2021-07-07

