簡介
OfficeIMO 是一個用于創建和操作 Microsoft Word (.docx) 和 Excel (.xlsx) 文檔的 .NET 庫。它基于 OpenXML SDK,提供了更簡單直觀的 API 接口。
OfficeIMO 的設計理念是簡單高效。專注于基本的 Word 處理需求,對于需要直接處理 Word 文檔而不需要功能豐富的復雜庫的項目來說,它是一個理想的選擇。
該項目最初是為了簡化 PowerShell 模塊 PSWriteOffice 中的文檔生成流程而開發,現已成為適用于整個 .NET 社區的通用庫。
平臺支持與兼容性
| |
| .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 |
? 測試覆蓋率:Codecov 鏈接
? 持續集成狀態:GitHub Actions CI
核心功能列表
Word 功能
- ? ?? 添加段落并設置樣式(加粗、顏色、對齊方式)
- ? ?? 表格操作(添加行/列、合并單元格、設置邊框)
- ? ?? 內容控件(StructuredDocumentTag)
使用示例
Nuget安裝
dotnet add package OfficeIMO.Word
基礎文檔創建
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
}
頁眉頁腳設置
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();
// ... 其他節配置 ...
document.Save(true);
}
內容控件操作
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 編輯過