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);

  • 相关阅读:
    UIButton中setTitleEdgeInsets和setImageEdgeInsets的使用
    关于自定义导航条UIBarButtonItem偏移的问题
    iOS端使用二维码扫描(ZBarSDK)和生成(libqrencode)功能
    CocoaPods安装和使用教程
    IOS中NSUserDefaults的用法(轻量级本地数据存储) (转)
    UIPickerView简单选择器的基本使用
    [原]Unity手游之路<三> 基于Unity+Java的聊天室源码
    [原]UML建模语言进阶
    [原]Java多线程编程学习笔记之九:使用wait/notify/notifyAll实现线程间通信的几点说明
    [原]MySQL的表分区
  • 原文地址:https://www.cnblogs.com/zbo/p/1872436.html
Copyright © 2011-2022 走看看