简介
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 编辑过