使用OpenXML类库, 以编程的方式来访问PowerPoint, Word, Excel等文档, 有时能够为我们批量编辑文档提供方便。

最近项目中遇到的两个任务是: 1. 替换文档中的图片的Alt Text信息。2. 替换文档中超级链接的ScreenTip信息。 这里的文档是PPT和Word。如果要手动打开Word文档, 然后一个一个图片进行替换, 挺浪费时间的, 其次, Word也没有提供图片Alt Text的查找替换功能, 所以, 就想编程实现批量查找和替换。

首先, 安装OpenXML SDK, 通过Nuget Manager.

Install-Package DocumentFormat.OpenXml 

然后加入对命名空间的引用。

using DocumentFormat.OpenXml.Office;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Drawing.Wordprocessing;

在Word中, Image图片的存储XML文档格式如下:

        <w:drawing>
<wp:inline distT="0" distB="0" distL="0" distR="0">
<wp:extent cx="2743438" cy="2792210"/>
<wp:effectExtent l="0" t="0" r="0" b="8255"/>
<wp:docPr id="1" name="Picture 1" descr="this is alt text description of horse icon." title="title of horse Icon"/>
<wp:cNvGraphicFramePr>
<a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>
</wp:cNvGraphicFramePr>
<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:nvPicPr>
<pic:cNvPr id="1" name="1.png"/>
<pic:cNvPicPr/>
</pic:nvPicPr>
<pic:blipFill>
<a:blip r:embed="rId6">
<a:extLst>
<a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}">
<a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/>
</a:ext>
</a:extLst>
</a:blip>
<a:stretch>
<a:fillRect/>
</a:stretch>
</pic:blipFill>
<pic:spPr>
<a:xfrm>
<a:off x="0" y="0"/>
<a:ext cx="2743438" cy="2792210"/>
</a:xfrm>
<a:prstGeom prst="rect">
<a:avLst/>
</a:prstGeom>
</pic:spPr>
</pic:pic>
</a:graphicData>
</a:graphic>
</wp:inline>
</w:drawing>

Word实现查找图片Alt Text的代码:

            using (WordprocessingDocument doc = WordprocessingDocument.Open(file, false))
{
MainDocumentPart mainPart = doc.MainDocumentPart; StringBuilder sb = new StringBuilder(); var imageParts = mainPart.ImageParts;
int imageIndex = ;
foreach (var image in imageParts)
{
imageIndex++;
string id = mainPart.GetIdOfPart(image);
var drawings = mainPart.Document.Body.Descendants<Drawing>();
string title = string.Empty;
string description = string.Empty;
foreach (var drawing in drawings)
{
if (drawing.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault() != null &&
drawing.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault().Embed == id)
{
title = drawing.Descendants<Inline>().First().DocProperties.Title != null ? drawing.Descendants<Inline>().First().DocProperties.Title.ToString() : string.Empty;
description = drawing.Descendants<Inline>().First().DocProperties.Description != null ? drawing.Descendants<Inline>().First().DocProperties.Description.ToString() : string.Empty;
}
} sb.AppendLine(string.Format("{0}: {1}={2}", imageIndex, title, description));
}

PPT实现图片Alt Text的查找代码如下:

using (PresentationDocument doc = PresentationDocument.Open(file, false))
{
StringBuilder sb = new StringBuilder(); int sdIndex = ;
foreach (var part in doc.PresentationPart.SlideParts)
{
sdIndex++;
int picIndex = ;
var imageParts = part.GetPartsOfType<ImagePart>();
foreach (var imagePart in imageParts)
{
picIndex++;
var picture = part.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Picture>().Where(p =>
p.BlipFill.Blip.Embed == part.GetIdOfPart(imagePart)).FirstOrDefault();
var title = picture.NonVisualPictureProperties.NonVisualDrawingProperties.Title;
var description = picture.NonVisualPictureProperties.NonVisualDrawingProperties.Description;
sb.AppendLine(string.Format("{0}-{1}: {2}={3}", sdIndex, picIndex, title, description));
}
} textToReturn = sb.ToString();
}

在Word中, 超级链接的XML代码是:

      <w:hyperlink r:id="rId7" w:tooltip="Baidu Company" w:history="1">
<w:r w:rsidR="00007220" w:rsidRPr="00FC5FDE">
<w:rPr>
<w:rStyle w:val="Hyperlink"/>
</w:rPr>
<w:t>www.baidu.com</w:t>
</w:r>
</w:hyperlink>

word实现超链接ScreenTip的查找:

            using (WordprocessingDocument doc = WordprocessingDocument.Open(file, false))
{
MainDocumentPart mainPart = doc.MainDocumentPart;
var hyperlinks = mainPart.Document.Body.Descendants<Hyperlink>(); StringBuilder sb = new StringBuilder(); int hlIndex = ;
foreach (var hyperlink in hyperlinks)
{
hlIndex++;
string url = string.Empty; var hyperlinkRelationships = mainPart.HyperlinkRelationships;
foreach (var item in hyperlinkRelationships)
{
if (item.Id == hyperlink.Id)
{
url = item.Uri.OriginalString;
break;
}
} string toolTip = hyperlink.Tooltip;
sb.AppendLine(string.Format("{0}: {1}={2}", hlIndex, url, toolTip));
} textToReturn = sb.ToString(); }

PPT实现超链接ScreenTip的查找:

            using (PresentationDocument doc = PresentationDocument.Open(file, false))
{
StringBuilder sb = new StringBuilder(); int sdIndex = ;
foreach (var part in doc.PresentationPart.SlideParts)
{
sdIndex++;
var hyperLinks = part.Slide.Descendants<DocumentFormat.OpenXml.Drawing.HyperlinkType>();
int hlIndex = ;
foreach (var hyperLink in hyperLinks)
{
hlIndex++;
string url = string.Empty;
foreach (var item in part.HyperlinkRelationships)
{
if (item.Id == hyperLink.Id)
{
url = item.Uri.Authority;
break;
}
}
var tooTip = hyperLink.Tooltip; sb.AppendLine(string.Format("{0}-{1}: {2}={3}", sdIndex, hlIndex, url, tooTip));
} } textToReturn = sb.ToString();
}

使用OpenXML操作Office文档的更多相关文章

  1. apache poi操作office文档----java在线预览txt、word、ppt、execel,pdf代码

    在页面上显示各种文档中的内容.在servlet中的逻辑 word: BufferedInputStream bis = null;  URL url = null;  HttpURLConnectio ...

  2. 黄聪:利用OpenXml生成Word2007文档(转)

    原文:http://blog.csdn.net/francislaw/article/details/7568317 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 一Op ...

  3. 利用OpenXml生成Word2007文档

    一.OpenXml简介 利用C#生成Word文档并非一定要利用OpenXml技术,至少可以使用微软提供的Office相关组件来编程,不过对于Office2007(确切的说是Word.Excel和Pow ...

  4. Java实现office文档与pdf文档的在线预览功能

    最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...

  5. 基于MVC4+EasyUI的Web开发框架经验总结(8)--实现Office文档的预览

    在博客园很多文章里面,曾经有一些介绍Office文档预览查看操作的,有些通过转为PDF进行查看,有些通过把它转换为Flash进行查看,但是过程都是曲线救国,真正能够简洁方便的实现Office文档的预览 ...

  6. 怎么给我的Office文档加密

    很多的用户朋友都可以熟练的使用office中的Word.Excel和PowerPoint文档,但大家对Office文档加密方式了解的并不多.Advanced Office Password Recov ...

  7. [转载]基于MVC4+EasyUI的Web开发框架经验总结(8)--实现Office文档的预览

    在博客园很多文章里面,曾经有一些介绍Office文档预览查看操作的,有些通过转为PDF进行查看,有些通过把它转换为Flash进行查看,但是过程都是曲线救国,真正能够简洁方便的实现Office文档的预览 ...

  8. java将office文档pdf文档转换成swf文件在线预览

    第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux,solaris等操作系统上执行. 主要模块有writer(文 ...

  9. 海量Office文档搜索

    知识管理系统Data Solution研发日记之十 海量Office文档搜索   经过前面两篇文章的介绍,<分享制作精良的知识管理系统 博客备份程序 Site Rebuild>和<分 ...

随机推荐

  1. R----Shiny包介绍学习

    为什么用Shiny Shiny让数据分析师写完分析与可视化代码后,稍微再花几十分钟,就可以把分析代码工程化,将分析成果快速转化为交互式网页分享给别人.所以,如果你是一名使用R的数据分析师,选择Shin ...

  2. [问题2014A01] 解答一(第一列拆分法,由张钧瑞同学提供)

    [问题2014A01] 解答一(第一列拆分法,由张钧瑞同学提供) (1)  当 \(a=0\) 时,这是高代书复习题一第 33 题,可用升阶法和 Vander Monde 行列式来求解,其结果为 \[ ...

  3. Linux变量

    变量:(大的分为环境变量与本的变量) 本地变量: 本地变量在用户现在的shell生命期的脚本中使用.例如,本地变量file-name="loop.doc",这个值只在用户当前she ...

  4. mac 启动apache + php

    一.启动Apache 在终端里输入命令,启动 Apache: sudo apachectl start 关闭 Apache: sudo apachectl stop 重启 Apache:sudo ap ...

  5. Android属性动画完全解析(上),初识属性动画的基本用法

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/43536355 在手机上去实现一些动画效果算是件比较炫酷的事情,因此Android系 ...

  6. 临时文件相关的v$tempfile v$sort_usage与V$tempseg_usage

    SQL> select username,user,segtype,segfile#,segblk#,extents,segrfno# from v$sort_usage; SEGFILE#代表 ...

  7. Android 广播机制概论

    Android 中的每一个应用程序都可以对自己感兴趣的广播进行注册,这样,该程序就只会接收到自己所关心的广播内容,这些广播可能是来自于系统的,也可能是来自于其他应用程序. 广播分为2种: 1.标准广播 ...

  8. java 注释

    单行注释// 多行注释/*  */ 注释并写入javadoc /**  */ // 这是单行注释的示例 /* 这个也是单行注释的示例 */ /* 这是第一个Java程序 *它将打印Hello Worl ...

  9. MySQL限时解答

    MySQL在国内各个行业的使用率越来越高,使用场景也越多,相应的遇到的疑惑也越来越多.在遇到这些问题之后,目前已有的解决途径有 1.培训(这是从长计议的方式,不能解决燃眉之急) 2.BBS(目前BBS ...

  10. SPSS数据分析—最小一乘法

    线性回归最常用的是以最小二乘法作为拟合方法,但是该方法比较容易受到强影响点的影响,因此我们在拟合线性回归模型时,也将强影响点作为要考虑的条件.对于强影响点,在无法更正或删除的情况下,需要改用更稳健的拟 ...