使用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. Android 自动化测试 Emmagee

    Emmagee 是一个性能测试小工具 用来监控指定被测应用在使用过程中占用机器的CPU, 内存,流量资源的性能小工具 阅读目录 Emmagee 介绍 Emmagee是网易杭州研究院QA团队开发的一个简 ...

  2. Maven学习(四)-- 生命周期和插件

    标签(空格分隔): 学习笔记 Maven生命周期是抽象的,不做任何实际的工作,在Maven的设计中,实际的任务都交由插件来完成. 每个构件步骤都可以绑定一个或者多个插件行为,而且Maven为大多数构建 ...

  3. django admin下拉列表不显示值,显示为object的处理

    问题:模板中创建form表单中的下拉列表, 前台打开页面显示object,而不是值,如图: 尝试了多种办法无果,最后解决了,处理办法是修改models.py,原来的model: class Techn ...

  4. 5----table类型

    table类型是非常重要的Lua数据类型,也是Lua唯一能描述数据结构的类型 table类型可以很灵活的描述多种数据结构,其本身是基于键值对的形式存储数据的 字典结构 字典结构的table 的两种创建 ...

  5. 安装eclipse插件时出现问题

    有时候我们安装eclipse插件时,会无法找到repository,这个时候去除掉多余的包,可能就行了.以下例子是安装spring插件,如果全选的话无法安装所有的插件,最终会失败 2.这时我们可以去掉 ...

  6. 转!!mybatis在xml文件中处理大于号小于号的方法

    第一种方法: 用了转义字符把>和<替换掉,然后就没有问题了. SELECT * FROM test WHERE 1 = 1 AND start_date  <= CURRENT_DA ...

  7. cube定时器延时不准确原因

    昨天晚上测试32cube配置好定时器,以1ms为一次中断,然后在程序中做了一个1s的延时,结果发现实际延时5s左右,百思不得其解,仔细查看cube配置也没问题.最后我打开生成工程文件夹里面的ioc文件 ...

  8. matlab实现感知机算法--统计学习小灶

    clear all; clc; %% %算法 %输入:训练数据集T = {(x1,y1),(x2,y2),...,(xn,yn)};学习率η %输出:w,b;感知机模型f(x) = sign(w*x+ ...

  9. MVP -----个人理解与示例(android例子 实现)

    MVP 也就是Model View Presenter模式,是建立一个工程的一种模式. ======================================================== ...

  10. springmvc__SimpleUrlHandlerMapping(对访问地址进行加工,以键值对的形式)

    1.配置web.xml(这里配置url-pattern为/) <!-- 编码过滤器 --> <filter> <filter-name>characterEncod ...