word的类库使用的是word2007版本的类库,类库信息见下面图片,折腾了半天,终于找到入口,网上 很多说的添加或者修改word的高级属性中的自定义属性都是错误的,感觉都是在copy网上的代码,自己终于摸索成功了,Mark下。

直接上代码,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Core;
using System.Reflection; namespace TestWord
{
/// <summary>
/// 从传入的word文档中替换掉指定书签的内容,主要是为了解决封面中的内容
/// 抽取命令:
/// xx.exe -p D:/temp/test.doc D:/result/mappting.txt
///
/// mappting.txt 文件是替换test.doc文档中标签的匹配文件,比如哪个标签的内容需要替换为其他的值
/// </summary>
class PageExtractor : IExtractor
{ private object oMissing = System.Reflection.Missing.Value; //标准页眉要替换的值在mapping.txt文件中存储的key
private String TB_YEMEI_GJB = "TB_YEMEI_GJB"; //写入word的高级属性中的内容,需要设置为整形的高级属性名
private String[] m_oIntegerAdvPropertyNames = new String[]{ "密级","稿件"}; //写入word的高级属性中的内容,需要设置为boolean
private String[] m_oBoolAdvPropertyNames = new String[] { "TRS" }; /// <summary>
/// 从指定word中抽取出word正文
/// </summary>
/// <param name="_sSourceWordPath"></param>
/// <returns></returns>
public bool execute(string[] args)
{
_Application oWord = WordProcessHelper.getInstance().getApplication();
_Document oDoc = null;
String _sWordPath = "";
LogServer currLogServer = LogServer.getInstance(); try
{
//1.参数需要长度为3,第一个是“-p”,第二个是“要抽取的word路径”,第三个是“匹配的书签替换文件”
if (args.Length < 3)
{
throw new Exception("替换封面时传入的参数个数至少为3个,第一个是‘-p’,第二个是‘要抽取的word路径’,第三个是标签‘匹配的UTF-8编码的txt文件内容’,第四个是文档的高级属性内容");
} _sWordPath = args[1];//获取要抽取的原word路径
if (!File.Exists(_sWordPath))
{
throw new Exception("Word文件[" + _sWordPath + "]不存在!");
} String sMappingFilePath = args[2];
if (CMyString.isEmpty(sMappingFilePath))
{
throw new Exception("没有传入替换doc文件内容的匹配文件路径!");
} //1.读取需要替换的文件内容
Properties mappingProperties = new Properties(sMappingFilePath);
if (mappingProperties.size() <= 0)
{
currLogServer.writeLogLine("文件[" + sMappingFilePath + "]中要替换的内容为空!");
return true;
} //2.读取word中标签
DateTime beginDateTime = new DateTime();
object oDocFilePath = _sWordPath;
object oReadOnly = false;
object oAddToRecentFiles = false;
oDoc = oWord.Documents.Open(ref oDocFilePath, ref oMissing, ref oReadOnly, ref oAddToRecentFiles, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //3.获取标签名与对应的Range对象的对应关系
Hashtable oBookIdToRangeMap = getBookIdToRange(oDoc, mappingProperties);
if (oBookIdToRangeMap == null || (oBookIdToRangeMap.Count == 0))
{
return true;
} //4.替换Range对象的内容为mapping文件中的属性值
replaceMappingContent(oDoc, oBookIdToRangeMap, mappingProperties); //5.替换页眉
Range allRange = oDoc.Range(ref oMissing, ref oMissing);
Sections allSections = allRange.Sections;
currLogServer.writeLogLine("开始替换[" + _sWordPath + "]页眉."); if (allSections != null && (allSections.Count > 0))
{
String sTBYeMeiGJB = mappingProperties.getPropertyAsString(TB_YEMEI_GJB, false);
currLogServer.writeLogLine("[" + _sWordPath + "]页眉要替换的值为:" + sTBYeMeiGJB);
sTBYeMeiGJB = CMyString.showEmpty(sTBYeMeiGJB);
for (int i = 1; i <= allSections.Count; i++)
{
Section aSection = allSections[i];
if (aSection == null)
{
continue;
} //设置奇数页和偶数页的页眉
aSection.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = sTBYeMeiGJB;
aSection.Headers[WdHeaderFooterIndex.wdHeaderFooterEvenPages].Range.Text = sTBYeMeiGJB;
}
} DateTime endDateTime = new DateTime();
String sTimeDuration = DateTimeHelper.dateDiff(beginDateTime, endDateTime);
currLogServer.writeLogLine("[" + _sWordPath + "]页眉替换完成,用时:" + sTimeDuration); //TDO:写入国军标的一些标准属性
//读取需要写入到文档高级属性的
if (args.Length < 4) {
return true;
} String sAdvancePropertyFilePath=args[3];
if (CMyString.isEmpty(sAdvancePropertyFilePath)) {
return true;
}
Properties advanceProperties = new Properties(sAdvancePropertyFilePath);
if (advanceProperties.size() <= 0)
{
currLogServer.writeLogLine("文件[" + sAdvancePropertyFilePath + "]中要写入的高级属性内容为空!");
return true;
} //写入属性
currLogServer.writeLogLine("[" + _sWordPath + "]开始写入高级属性.");
writeDocAdvanceProperty(oDoc, advanceProperties);
currLogServer.writeLogLine("[" + _sWordPath + "]高级属性写入完成."); //TODO:返回成功标记
return true; }
catch (Exception ex)
{
currLogServer.writeLogLine("页眉替换从文件[" + _sWordPath + "]时发生错误:"+ex.Message);
throw new Exception("页眉替换从文件[" + _sWordPath + "]时发生错误", ex);
}
finally
{
//关闭当前文档
object saveOption = WdSaveOptions.wdSaveChanges;
if (oDoc != null)
{
oDoc.Close(ref saveOption, ref oMissing, ref oMissing);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
} }
} /// <summary>
/// 把指定的高级属性的Properties中的内容写入到文档的高级属性中
/// </summary>
/// <param name="oDoc"></param>
/// <param name="advanceProperties"></param>
private void writeDocAdvanceProperty(_Document oDoc, Properties advanceProperties) {
if (oDoc == null || (advanceProperties == null) || (advanceProperties.size()<=0))
{
return;
} //遍历Properties属性
Hashtable allAdvanceProperties=advanceProperties.getProperties();
if (allAdvanceProperties == null || (allAdvanceProperties.Count <= 0)) {
return;
} //获取高级属性对象
object oDocCustomProps = oDoc.CustomDocumentProperties;
Type typeDocCustomProps = oDocCustomProps.GetType(); //遍历集合
foreach (String sPropName in allAdvanceProperties.Keys)
{
String sValue = (String)allAdvanceProperties[sPropName];
sValue = CMyString.showEmpty(sValue); //获取属性名的类型
Object oPropItemObj = getPropertyObjByName(oDocCustomProps, typeDocCustomProps, sPropName);
if (oPropItemObj == null)
{
//不存在,则添加
MsoDocProperties oPropertType = getPropertyTypeByName(sPropName);
object[] oArgs = {sPropName,false,
oPropertType,
sValue};
typeDocCustomProps.InvokeMember("Add", BindingFlags.Default |
BindingFlags.InvokeMethod, null,
oDocCustomProps, oArgs);
}
else {
//已经存在,则覆盖属性
Type typeItemProp = oPropItemObj.GetType();
typeItemProp.InvokeMember("Value",
BindingFlags.Default | BindingFlags.SetProperty,
null, oPropItemObj,
new object[] { sValue });
}
} } /// <summary>
/// 从指定的自定义高级属性中查找指定名称的Item对象,如果没有找到,则返回null
/// </summary>
/// <param name="oDocCustomProps"></param>
/// <param name="typeDocCustomProps"></param>
/// <param name="_sPropertyName"></param>
/// <returns></returns>
private object getPropertyObjByName(object oDocCustomProps,Type typeDocCustomProps, String _sPropertyName)
{
if (CMyString.isEmpty(_sPropertyName)) {
return null;
}
if (oDocCustomProps == null || typeDocCustomProps == null) {
return null;
} //通过反射去查找对象
//获取值
object oPropItem = null;
try
{
oPropItem = typeDocCustomProps.InvokeMember("Item",
BindingFlags.Default |
BindingFlags.GetProperty,
null, oDocCustomProps,
new object[] { _sPropertyName });
}
catch (Exception ex) {
//TODO:由于没有找到判断是否存在属性的接口,所以这里通过Item来判断,如果属性不存在,则会报错,这里粗鲁的忽略掉异常
oPropItem = null;
} //返回结果
return oPropItem;
} /// <summary>
/// 根据属性名获取该属性对应的类型
/// </summary>
/// <param name="sPropName"></param>
/// <returns></returns>
private MsoDocProperties getPropertyTypeByName(String sPropName)
{
if (CMyString.isEmpty(sPropName)) {
return MsoDocProperties.msoPropertyTypeString;
}
//判断是否是整形
bool bInStrArray = CMyList.isInStrArray(sPropName, m_oIntegerAdvPropertyNames, true);
if (bInStrArray) {
return MsoDocProperties.msoPropertyTypeNumber;
}
//判断是否是bool型
bInStrArray = CMyList.isInStrArray(sPropName, m_oBoolAdvPropertyNames, true);
if (bInStrArray) {
return MsoDocProperties.msoPropertyTypeBoolean;
} //默认返回字符串
return MsoDocProperties.msoPropertyTypeString;
} /// <summary>
/// 返回指定文档中需要替换属性的书签名称与Range对象HashTable对象
/// </summary>
/// <param name="oDoc"></param>
/// <param name="mappingProperties"></param>
/// <returns></returns>
private Hashtable getBookIdToRange(_Document oDoc, Properties mappingProperties) {
//1.参数校验
Hashtable oBookIdToRangeMap = new Hashtable();
if (oDoc == null || (mappingProperties == null)) {
return oBookIdToRangeMap;
} //获取标签内容
Bookmarks allBookMars = oDoc.Bookmarks;
for (int i = 1; i <= allBookMars.Count; i++)
{
object oIndex = i;
Bookmark aBookMark = allBookMars.get_Item(ref oIndex);
if (aBookMark == null)
{
continue;
}
String sBookName = aBookMark.Name;
if (CMyString.isEmpty(sBookName)) {
continue;
} //是否包含在要替换的属性集合中
if (!mappingProperties.contains(sBookName,true)) {
continue;
} //压入书签名称与Range对象集合中
oBookIdToRangeMap.Add(sBookName.Trim().ToUpper(), aBookMark.Range);
} //返回集合中
return oBookIdToRangeMap;
} /// <summary>
/// 根据 mappingProperties中的属性值替换 oBookIdToRangeMap 指定Range对象的内容,并设置Range对象的书签名称
/// </summary>
/// <param name="oDoc"></param>
/// <param name="oBookIdToRangeMap"></param>
/// <param name="mappingProperties"></param>
private void replaceMappingContent(_Document oDoc,Hashtable oBookIdToRangeMap, Properties mappingProperties)
{
//1.参数校验
if (oDoc == null || (oBookIdToRangeMap == null) || (mappingProperties == null)) {
return;
} //2.遍历Map对象
foreach (String sBookIdKey in oBookIdToRangeMap.Keys)
{
Range currBookRange = (Range)oBookIdToRangeMap[sBookIdKey];
if (currBookRange == null) {
continue;
} //获取替换的值
String sReplaceValue = mappingProperties.getPropertyAsString(sBookIdKey,true);
sReplaceValue = CMyString.showEmpty(sReplaceValue);
currBookRange.Text = sReplaceValue; //重新设置书签
if (!oDoc.Bookmarks.Exists(sBookIdKey))
{
object oTempBookRange = currBookRange;
oDoc.Bookmarks.Add(sBookIdKey, ref oTempBookRange);
}
}
} }
}

C# 操作 Word 修改word的高级属性中的自定义属性2的更多相关文章

  1. C# 操作 Word 修改word的高级属性中的自定义属性

    为 Microsoft Word 创建自动化客户端 启动 Visual Studio .NET. 在文件菜单上,单击新建,然后单击项目.从 Visual C# 项目类型中选择 Windows 应用程序 ...

  2. jQuery操作标签--样式、文本、属性操作, 文档处理

    1.样式 2.文本 3.属性操作 全选,反选效果 4.文档处理 操作标签 一.样式操作 样式类: addClass(); // 添加指定的css类名 removeClass(); //移除指定的css ...

  3. 全面了解POI操作Microsoft Office(Word、Excel、PowerPoint)

    POI 与 Microsoft Office 1. POI 简介 POI 是 Apache 下的 Jakata 项目的一个子项目,主要用于提供 java 操作 Microsoft Office 办公套 ...

  4. 如何修改word的项目编号

    在操作word文档时,有时会遇到word文档中的项目编号不是自己需要的,并造成word项目编号的混乱,如何word中的两级项目编号不统一,为解决会word的项目编号混乱问题,小编将教大家如何修改wor ...

  5. C#学习笔记(33)——批量修改word标题

    说明(2017-12-22 11:20:44): 1. 因为数学脚本的主标题和副标题没有格式,目录导航里不显示,修改的时候不好定位,所以需要改成下图格式: 2. 问题的难点有两个,一个是word的操作 ...

  6. 教您如何在Word的mathtype加载项中修改章节号

    在MathType数学公式编辑器中,公式编号共有五部分内容:分别是章编号(Chapter Number).节编号(Section Number).公式编号(Equation Number).括号(En ...

  7. ASP.NET MVC深入浅出(被替换) 第一节: 结合EF的本地缓存属性来介绍【EF增删改操作】的几种形式 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery ) 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法 第六节: EF高级属性(二) 之延迟加载、立即加载、显示加载(含导航属性) 第十节: EF的三种追踪

    ASP.NET MVC深入浅出(被替换)   一. 谈情怀-ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态 ...

  8. 利用python批量修改word文件名的方法示例

    利用python批量修改word文件名的方法示例 最近不小心把硬盘给格式化了,由于当时的文件没有备份,所以一下所有的文件都没有了,于是只能采取补救措施,用文件恢复软件恢复了一部分的数据出来,但是恢复完 ...

  9. 怎么批量修改Word表格的宽度

    怎么批量修改Word表格的宽度 怎么批量修改Word表格的宽度呢.Word表格可根据窗口自动调整表格宽度,使得所有的表格宽度和页面宽度一样.当页面设置了新的页边距后,所有的表格都需要调整新的宽度.或者 ...

随机推荐

  1. linux下面的查找

    locate:     速度快     不是实时的,每天定时执行把结果导入数据库     模糊匹配     updatedb  --手动生成文件数据库,执行时间较长   find:     实时查找 ...

  2. DataGridView 绑定数据后修改列类型

    dataGridView1.DataSource = dt; dataGridView1.Columns.RemoveAt(); //删除要被替换的列 DataGridViewLinkColumn l ...

  3. [Linux]root默认密码问题

    Linux/Ubuntu root默认密码问题   Ubuntu安装后root是没有默认的密码的,因为你还没给root设置密码,你第一个 user 是在 admin 组,他可以给 root 设置密码, ...

  4. Python Mixin混入的使用方法

    DEMO # encoding=utf-8 __author__ = 'kevinlu1010@qq.com' class Base(): def f1(self): print 'I am f1 i ...

  5. 由12306出错想到的div垂直居中的问题

    今天想看看元旦回家还有没有余票,偷偷的打开了12306,开始查询回家的车票,结果发现,竟然查询不出来,再查直接出错了 看到这个很郁闷,很纠结,但是突然想到了最近一直想实现div垂直居中,赶紧试了一下1 ...

  6. 使用WiX Toolset创建.NET程序发布Bootstrapper(安装策略管理)(一)-----初识WiX (转)

    原文地址:http://blog.csdn.net/rryqsh/article/details/8274832 Visual Studio 打包安装七宗罪 开发.NET的人,肯定会使用Visual ...

  7. [HDOJ - 5282] Senior's String 【DP】

    题目链接:BZOJ - 5282 题目分析 LCS 就是用经典的 O(n^2) DP 解决,f[i][j] 表示 x 串前 i 个字符与 y 串前 j 个字符的 LCS 长度. f[i][j] = m ...

  8. Spring+MyBatis实践—中文乱码

    多种中文乱码问题及解决: jsp页面乱码 表单提交乱码 URL中文参数乱码 1.jsp页面乱码解决(2步): 新建jsp页面: <%@ page language="java" ...

  9. 如何使用 Java8 实现观察者模式?(上)

    [编者按]本文作者是 BAE 系统公司的软件工程师 Justin Albano.在本篇文章中,作者通过在 Java8 环境下实现观察者模式的实例,进一步介绍了什么是观察者模式.专业化及其命名规则,供大 ...

  10. ZOJ 3170 Friends

    点我看题目 题意 : 就是有n个人,m对关系,每对关系的两个人是好朋友,这个关系是相互的,如果有两个人的共同好朋友超过k个,那这两个人也会是好朋友的,给你m对关系,给你足够长的时间,问你还能增加几对关 ...