我们需要一些工具来开始 Open XML 的开发。

开发工具

推荐的开发工具是 Visual Studio 社区版。

开发工具:Visual Studio Community 2013

下载地址:http://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx

包含了 Visual Studio Professional 2013 全部功能,可以在学习环境中、学术研究、参与开源项目中免费使用。

当然,如果你有 Visual Studio 的 2012 版,或者 2013 版也可以使用。

下载源代码

GitHub 项目地址:https://github.com/officedev/open-xml-sdk

GitCafe 项目地址:https://gitcafe.com/msopentech_china/open-xml-sdk

在 GitCafe 的页面上,右上角的下载图标,可以直接下载源码,或者在它的下面是复制 Git 地址的按钮,灰色的按钮,不太明显,你可以直接通过 Git 来获取源码。

如果你已经使用 VS2013 ,那么直接就可以使用 Git 来获取源码了。

如果你没有使用 Visual Studio 社区版,也没有使用 Git, 也可以自己动手编译 Open XML SDK.

在获取的 Visual Studio 项目中包含预生成命令行,该命令行生成 PowerShell 脚本(和普通命令行生成脚本的方法基本相同),用于设置 AssemblyInfo.cs 版本字符串。要执行此预生成命令行,您必须按照前文所述的方法设置执行策略。如有多个 PowerShell 快捷方式,请确保使用正确的快捷方式进行 Visual Studio 安装。

如果收到错误提示“The command "cd C:\Users\Eric\Documents\Open-Xml-Sdk\ powershell ./SetAssemblyVersionString.ps1" exited with code 1”,那么您需要设置执行策略。您还可以从 Visual Studio 中运行另一个 PowerShell 脚本执行策略。要设置此执行策略:

  • 以管理员身份打开命令提示(非 PowerShell 控制台)。
  • 输入以下命令:

C:\windows\system32>c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -command set-executionpolicy unrestricted

这一段的工作就是为了自动生成 AssemblyInfo.cs 这个文件,生成的结果如下:

// Copyright (c) Microsoft Open Technologies, Inc.  All rights reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
using System.Security; // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DocumentFormat.OpenXml")]
[assembly: AssemblyDescription("Open XML Format SDK 2.5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")]
[assembly: AssemblyProduct("Open XML Format SDK 2.5")]
[assembly: AssemblyCopyright("© 2014 Microsoft Open Technologies, Inc. Licensed under the Apache License, Version 2.0.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5439c83f-c709-4487-b979-ce607e81b63e")] // Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.5.5893.1380")]
[assembly: AssemblyFileVersion("2.5.5893.1380")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: SecurityTransparent]

编译完成之后,就可以得到一个名为 DocumentFormat.OpenXml.dll 的程序集了。

使用 OpenXML SDK

生成 Word 文档

在页面 https://msdn.microsoft.com/zh-cn/library/office/gg278308.aspx 中,微软提供了 Word 文件结构的一个简单说明,并提供了一个简单的示例来生成一个基本的 Word 文档。我们可以修改成如下的代码,通过命令行接收两个参数,第一个参数是 Word 文件的名称,第二个参数是文件的内容。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Spreadsheet; namespace OpenXMLSDK_App
{
class Program
{
static void Main(string[] args)
{
string path = args[];
string msg = args[];
CreateWordDoc(path, msg);
} public static void CreateWordDoc(string filepath, string msg)
{
using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = doc.AddMainDocumentPart(); // Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run()); // String msg contains the text, "Hello, Word!"
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(msg));
}
}
}
}

我们如下使用生成的程序。

.\OpenXMLSDK_App.exe hello.docx "Hello, world."

这样将会生成一个名为 hello.docx 的文件。生成出来的文件实际上是一个 ZIP 文件,可以将文件的扩展名修改为 .zip,打开之后结构如下。

在 word 文件夹中有一个 document.xml 文件,其中的内容如下所示:

<?xml version="1.0" encoding="utf-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
<w:p>
<w:r>
<w:t>Hello, world.</w:t>
</w:r>
</w:p>
</w:body>
</w:document>

w 是 XML 的命名空间,document 表示主文档部件的根元素,body 类似于 HTML 中的 body, 包含主文章的块级别结构集合的容器,p 表示一个段落,r 表示一段连续的文本,t 一段文字。

生成 Excel 文档

在页面 https://msdn.microsoft.com/zh-cn/library/office/gg278316.aspx 中,微软提供了 Excel 文档的说明和示例,其中的 CreateSpreasheetWorkbook 静态方法可以直接粘贴到刚才的类中。

public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook); // Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook(); // Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData()); // Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets()); // Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = , Name = "mySheet" };
sheets.Append(sheet); workbookpart.Workbook.Save(); // Close the document.
spreadsheetDocument.Close();
}

写一段程序调用这个方法,就会得到一个 xlsx 文件,其中包含了一个 mySheet 的页面。

生成的 XML 内容如下:

<?xml version="1.0" encoding="utf-8"?>
<x:workbook xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:sheets>
<x:sheet name="mySheet" sheetId="1" r:id="Rddc7711f116045e5" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
</x:sheets>
</x:workbook>

程序很容易读懂,我们通过简单的代码就可以生成 Word 或者 Excel 文件了。

下载和编译 Open XML SDK的更多相关文章

  1. Open XML SDK 在线编程黑客松

    2015年2月10日-3月20日,开源社 成员 微软开放技术,GitCafe,极客学院联合举办" Open XML SDK 在线编程黑客松 ",为专注于开发提高生产力的应用及服务的 ...

  2. android开发(0):android studio的下载安装与简单使用 | sdk的安装与编译运行

    android studio,简称AS,是集成开发环境,所谓集成,就是集编辑.编译.调试.打包等于一体.简单来说,通过AS,就可以开发出在android系统上运行的APP. 我使用的是macos系统. ...

  3. Open Xml SDK Word模板开发最佳实践(Best Practice)

    1.概述 由于前面的引文已经对Open Xml SDK做了一个简要的介绍. 这次来点实际的——Word模板操作. 从本质上来讲,本文的操作都是基于模板替换思想的,即,我们通过替换Word模板中指定元素 ...

  4. Open Xml SDK 引文

    什么是Open Xml SDK? 什么是Open Xml? 首先,我们得知道,Open Xml为何物? 我们还是给她起个名字——就叫 “开放Xml”,以方便我们中文的阅读习惯.之所以起开放这个名字,因 ...

  5. 下载和使用 Open XML PowerTools

    安装 Open XML SDK 2.5 首先,需要安装 Open XML SDK 2.5 ,从这个地址下载安装程序:http://www.microsoft.com/en-in/download/de ...

  6. Ubuntu10.04下载并编译Android4.3源代码

    注:转载或引用请标明出处    http://blog.csdn.net/luzhenrong45/article/details/9719433 去年用Ubuntu10.10成功下载并编译Andro ...

  7. 【转】Android 4.3源码的下载和编译环境的安装及编译

    原文网址:http://jingyan.baidu.com/article/c85b7a641200e0003bac95a3.html  告诉windows用户一个不好的消息,windows环境下没法 ...

  8. 【转】在Ubuntu上下载、编译和安装Android最新源代码

    原文网址:http://blog.csdn.net/luoshengyang/article/details/6559955 看完了前面说的几本书之后,对Linux Kernel和Android有一定 ...

  9. 在Ubuntu上下载、编译和安装Android最新源码

    看完了前面说的几本书之后,对Linux Kernel和Android有一定的认识了,是不是心里蠢蠢欲动,想小试牛刀自己编译一把Android源码了呢?一直习惯使用Windows系统,而Android源 ...

随机推荐

  1. 模型(modle)

    MVC模式三:模型操作数据库,之后注册变量于模板,之后用控制器的dispaly()方法显示; 一.跨控制器调用方法 因为控制器的实质是类,所以在该方法中造一个要调用的类的对象,调用他的方法; 比如,在 ...

  2. html5外包—长年承接html5外包业务:《Sencha Touch权威指南》下载

    <Sencha Touch权威指南>内容简介:如何才能全面而透彻地理解和掌握移动应用开发框架Sencha Touch并开发出令人心动的移动应用?<Sencha Touch权威指南&g ...

  3. 【VNC】Ubuntu14.04LTS下安装VNC View

    # apt-get install tightvncserver vnc4server gnome-panel gnome-settings-daemon metacity nautilus gnom ...

  4. Winform/WPF国际化处理

    1.Winfrom国际化处理方式 ==> Winform中国际化支持可将UI页面和.cs文件分开处理 处理窗体方式如下:1.选择Form窗体设置其--Language(默认中文--Default ...

  5. 案例:用Redis来存储关注关系(php版)

    Redis提供了丰富的数据类型,比起关系型数据库或者简单的Key-Value存储(比如Memcached)来,Redis的数据模型与实际应用的数据模型更相近.比如下面说到的好友关系的存储,原作者使用了 ...

  6. OpenGL®ES基础

    参考:http://www.cnblogs.com/salam/archive/2016/01/08/5113572.html http://blog.csdn.net/wangyuchun_799/ ...

  7. Linux命令(19)用户权限管理:chown

    linux用户权限: Linux/Unix 是多人多工作业系统,所有的档案皆有拥有者.利用 chown 可以将档案的拥有者加以改变. 一般来说,这个指令只有是由系统管理者(root)所使用,一般使用者 ...

  8. git push失败的解决办法(2)

    错误一:Cannot rebase: You have unstaged changes 解决办法: Cannot rebase: You have unstaged changes. 那说明有修改过 ...

  9. Nginx_修改Web服务器头信息(Header)里的Server值[转]

    http://blog.rekfan.com/?p=122 黑客攻击一个网站,往往需要了解服务器的架构,网站的架构等信息,了解了这些信息,就知道网站薄弱的地方在哪里了!    为了不让对方知道自己的w ...

  10. SharedPreferences实现自动登录记住用户名密码

    最近Android项目需要一个自动登录功能,完成之后,特总结一下,此功能依靠SharedPreferences进行实现.   SharedPreferences简介 SharedPreferences ...