C#使用Office Interop生成Word文档示例
本文介绍如何利用 C# 中的 Microsoft.Office.Interop.Word 库创建 Word 文件,详细展示了从建立文档对象、配置页面样式到动态填充表格数据的编程实现。
环境准备
此方法依赖于本地安装的 Microsoft Office (Word)。在 Visual Studio 项目中添加对 Microsoft.Office.Interop.Word 的引用即可使用相关类。
生成 Word 文档的操作步骤
第1步:初始化 COM 对象与文档
首先创建 Word Application 实例并添加一个新文档。同时定义占位符以便后续在文档末尾插入内容。
object Nothing = System.Reflection.Missing.Value;
object filename = _filename; // 目标文件路径
string strtitle = "任务导出";
object oEndOfDoc = "//endofdoc"; // 书签位置标识
第2步:配置页面布局(页眉与标题)
切换至页眉视图以插入页眉文字,并设置其右对齐。随后跳回主文档,添加居中大号字体标题。
// 设置页眉
WordApp.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("WPFOA任务导出");
WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
// 设置标题
Word.Paragraph oPara1 = WordDoc.Content.Paragraphs.Add(ref Nothing);
oPara1.Range.Text = strtitle;
oPara1.Range.Font.Name = "宋体";
oPara1.Range.Font.Size = 20;
oPara1.Range.Font.Bold = 1;
oPara1.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
第3步:循环插入表格与数据
遍历数据集(如 lst_task),在文档末尾定位光标并插入新表格。设置列宽、边框样式后填入具体文本。
// 获取文档末尾范围
Word.Range wrdRng = WordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
// 创建5行4列表格
Word.Table newTable = WordDoc.Tables.Add(wrdRng, 5, 4, ref Nothing, ref Nothing);
newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
// 填充示例数据
newTable.Cell(1, 1).Range.Text = "项目名称";
newTable.Cell(1, 2).Range.Text = "1";
// ... 其他单元格赋值 ...
// 合并最后一行的后三列用于描述
newTable.Cell(5, 2).Merge(newTable.Cell(5, 4));
newTable.Cell(5, 2).Range.Text = "任务描述内容";
第4步:保存文档与释放资源
执行 SaveAs 保存文件,关闭文档和应用程序。由于 COM 对象不会自动立即回收,建议显式调用 GC 或结束 WINWORD 进程以防止后台残留。
WordDoc.SaveAs(ref filename, ref Nothing, ...); // 简化参数省略
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
// 强制杀除可能残留的 Word 进程
try {
var procs = System.Diagnostics.Process.GetProcessesByName("WINWORD");
foreach (var p in procs) { if(p.MainWindowHandle == null) p.Kill(); }
} catch {}
注意事项与风险提醒
- 服务器端部署风险:微软官方并不支持在服务器环境(如 Windows Server/IIS)上非交互式运行 Office Interop。该方式可能导致死锁、权限错误或性能瓶颈,生产环境建议使用
OpenXML SDK等纯代码库替代。 - 并发限制:默认情况下 Word 实例无法并行处理多个请求,多线程调用时需注意线程同步问题。
以上就是使用 C# 和 Office Interop 生成 Word 文档的详细内容,更多关于 C# 办公软件自动化的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













