簡(jiǎn)介
OfficeIMO 是一個(gè)用于創(chuàng)建和操作 Microsoft Word (.docx) 和 Excel (.xlsx) 文檔的 .NET 庫(kù)。它基于 OpenXML SDK,提供了更簡(jiǎn)單直觀的 API 接口。
OfficeIMO 的設(shè)計(jì)理念是簡(jiǎn)單高效。專(zhuān)注于基本的 Word 處理需求,對(duì)于需要直接處理 Word 文檔而不需要功能豐富的復(fù)雜庫(kù)的項(xiàng)目來(lái)說(shuō),它是一個(gè)理想的選擇。
該項(xiàng)目最初是為了簡(jiǎn)化 PowerShell 模塊 PSWriteOffice 中的文檔生成流程而開(kāi)發(fā),現(xiàn)已成為適用于整個(gè) .NET 社區(qū)的通用庫(kù)。
平臺(tái)支持與兼容性
| |
| .NET Framework 4.7.2+、.NET Core 3.1+、.NET 5/6/7/8/9 |
| .NET Core 3.1+、.NET 5/6/7/8/9 |
| .NET Core 3.1+、.NET 5/6/7/8/9 |
? 測(cè)試覆蓋率:Codecov 鏈接
? 持續(xù)集成狀態(tài):GitHub Actions CI
核心功能列表
Word 功能
- ? ?? 設(shè)置文檔屬性(標(biāo)題、作者、關(guān)鍵詞等)
- ? ?? 添加段落并設(shè)置樣式(加粗、顏色、對(duì)齊方式)
- ? ?? 表格操作(添加行/列、合并單元格、設(shè)置邊框)
- ? ?? 超鏈接、書(shū)簽、分頁(yè)符、注釋
- ? ?? 內(nèi)容控件(StructuredDocumentTag)
使用示例
Nuget安裝
dotnet add package OfficeIMO.Word
基礎(chǔ)文檔創(chuàng)建
string filePath = Path.Combine("Support", "GitHub", "PSWriteOffice", "Examples", "Documents", "BasicDocument.docx");
using (WordDocument document = WordDocument.Create(filePath)) {
document.Title = "This is my title";
document.Creator = "Przemys?aw K?ys";
document.Keywords = "word, docx, test";
var paragraph = document.AddParagraph("Basic paragraph");
paragraph.ParagraphAlignment = JustificationValues.Center;
paragraph.Color = SixLabors.ImageSharp.Color.Red;
document.Save(true);
}
流式文檔操作
using var stream = new MemoryStream();
using (var document = WordDocument.Create(stream)) {
document.AddParagraph("Stream based document");
document.Save(stream);
}
stream.Position = 0;
using (var loaded = WordDocument.Load(stream)) {
Console.WriteLine(loaded.Paragraphs[0].Text);
}
保存為新文檔
using (WordDocument document = WordDocument.Create()) {
document.AddParagraph("Some text");
using var copy = document.SaveAs(filePath);
// document.FilePath 仍然是 null
// copy.FilePath 等于 filePath
}
頁(yè)眉頁(yè)腳設(shè)置
using (WordDocument document = WordDocument.Create(filePath)) {
document.Sections[0].PageOrientation = PageOrientationValues.Landscape;
document.AddParagraph("Test Section0");
document.AddHeadersAndFooters();
document.DifferentFirstPage = true;
document.DifferentOddAndEvenPages = true;
document.Sections[0].Header.First.AddParagraph().SetText("Test Section 0 - First Header");
document.Sections[0].Header.Default.AddParagraph().SetText("Test Section 0 - Header");
document.Sections[0].Header.Even.AddParagraph().SetText("Test Section 0 - Even");
document.AddPageBreak();
// ... 其他節(jié)配置 ...
document.Save(true);
}
內(nèi)容控件操作
using (WordDocument document = WordDocument.Create(filePath)) {
var sdt = document.AddStructuredDocumentTag("Hello", "MyAlias", "MyTag");
sdt.Text = "Changed";
document.Save(true);
}
using (WordDocument document = WordDocument.Load(filePath)) {
var tag = document.GetStructuredDocumentTagByTag("MyTag");
Console.WriteLine(tag.Text);
}
該文章在 2025/6/26 22:14:26 編輯過(guò)