C#操作word并格式化

1.    概述

C#基于com组件将数据导入到word中分栏并格式化。

2.    准备步骤

A.        在项目中添加引用Microsoft Word 11.0 Object Library

B.        引入命名空间

using Microsoft.Office.Core;

using MSWord = Word;

3.    思路

A.      首先创建word应用程序(MSWord.Application)word文档对象(MSWord.Document)

MSWord.Application wordApp;           //Word应用程序变量

MSWord.Document wordDoc;              //Word文档变量

B.      初始化并向word应用程序添加一个word文档。

wordApp = new MSWord.ApplicationClass(); //初始化

//由于使用的是COM库,因此有许多变量需要用Missing.Value代替

Object Nothing = Missing.Value;

wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

C.      设置分栏:分栏有整篇文档的分栏和选中部分的分栏

Ø        整篇文档的分栏:

直接设置wordDoc.PageSetup.TextColumns.SetCount(count);count为1-45的整数。

Ø        选中部分的分栏:

设置选中的区域Range,wordDoc.Range(ref start, ref end).Select(),start开始位置和end结束位置必须为oject,之后分栏wordDoc.Sections.PageSetup.TextColumns.SetCount(2), Sections表示刚选中的部分。

再加上object nt = WdBreakType.wdSectionBreakContinuous;

wordApp.ActiveDocument.Range(refend, ref end).InsertBreak(ref nt);具体意思不太清楚,但是如果不加就不能产生选中部分的分栏。

D.    设置字体的样式,段落的缩进:

Ø        首先要选中设置字体的区域,之后设置选中区域字体Font。

Ø        段落缩进IndentCharWidth(charcount),charcount表示缩进的字符,

Ø        段落的悬挂缩进TabHangingIndent(charcount).

E.      设置表格的样式:

//定义一个Word中的表格对象

MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, rows, columns, ref Nothing, ref Nothing);

Ø        合并单元格:

table.Cell(1, 1).Merge(table.Cell(2, 1));//表示从第几行的第几列到第几行的第几列合并。

Ø        设置重复标题行:

table.Rows[1].HeadingFormat = (int)WdConstants.wdToggle;

F.      设置文档格式并保存:

//WdSaveFormat为Word 2003文档的保持格式wdFormatDocument;

object format = MSWord.WdSaveFormat.wdFormatDocument;

//将wordDoc文档对象的内容保存为DOCX文档

wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//关闭wordDoc文档对象

wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);

//关闭wordApp组件对象

wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

原文地址:https://www.cnblogs.com/zbo/p/1872436.html