zoukankan      html  css  js  c++  java
  • 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);

  • 相关阅读:
    String substring(int start,int end)截取当前字符串中指定范围内的字符串
    String字符串是不变对象,内容一旦创建不可改变,若改变一定会创建新对象
    StringBuilder修改字符串内容,增,删,改,插
    startsWith(),endsWith()判断当前字符串是否是以给定字符串开始或结尾的
    length()返回当前字符串的字符个数
    indexOf()字符位置
    charAt()检测回文
    手把手教你猜字小游戏
    release 和 drain
    c专家编程 ,c语言运行时环境
  • 原文地址:https://www.cnblogs.com/zbo/p/1872436.html
Copyright © 2011-2022 走看看