SharePoint 2010 has established a new service called “Word Automation Services” to operate word files. This service will be installed when install SharePoint 2010. It is useful for archive documents or convert word format in server. But we need initialize and configure this service on Central Administration or PowerShell.(How to set up Word Automation Services? see:http://msdn.microsoft.com/en-us/library/ee557330(v=office.14).aspx)

After initialized, SharePoint 2010 will setup a database named:”WordAutomationServices_XXXX”. We can find the service status in Central Administration->Application Management->Service Applications->Manage services on server:

Make sure the service is started.

Call Word Automation Services

Next, we can use C# code to call the Word Automation Services. For example, this is a word file in Shared Documents, we need to convert the word file to pdf format and saved in another document library (named Docs), we can write code like this:

string siteUrl = "http://localhost";
string wordAutomationServiceName = "Word Automation Services";
using (SPSite spSite = new SPSite(siteUrl))
{ConversionJob job = new ConversionJob(wordAutomationServiceName);job.UserToken = spSite.UserToken;job.Settings.UpdateFields = true;job.Settings.OutputFormat = SaveFormat.PDF;job.AddFile(siteUrl + "/Shared%20Documents/Contract%20Management.docx",siteUrl + "/Docs/Contract%20Management.pdf");job.Start();
}

Note: Word Automation Services use a timer to process our job, so even we finished our process in code, we still cannot find the pdf file in document library. After a few minutes, the timer will complate our job, refresh the document library page we can see the pdf file. If we want to make the timer work frequently, we can go to Central Administration->Monitoring->Timer Jobs->Review job definitions, click the “Word Automation Services Timer Job”, change the “Recurring Schedule” value such as 1 minute. If we want to run the job immediately, we can click the "Run Now” button.

User Open XML SDK to generate word file

Open XML is a common standard format for Office files since Office 2007. We can use Open XML SDK to develop the application that combine the user define template and data (from database, SharePoint list, interface or other user input).

Open XML SDK is not contained in Visual Studio by default, so we must download the SDK from Microsoft.(Download address:http://www.microsoft.com/en-us/download/details.aspx?id=5124) After install the SDK, we can reference the component: DocumentFormat.OpenXml and WindowsBase.

In the code, we can read the template from disk or SharePoint document library. The template contains some special word than we will replace them by user data.

For example, there is a template, we need to fill the vender name, amount and date, so we can define the template like this:

Purchasing Contract

Vender:$Vender,

Description:bala bala~~~

Total Amount: $Amount

Signature Date:$Today

We save the template as a docx file in disk, and we can read the template by Open XML SDK and replace the words like this:

FileStream fs=new FileStream("Template.docx",FileMode.Open,FileAccess.Read);
byte[] byteArray = new byte[fs.Length];
fs.Read(byteArray, 0, (int)(fs.Length));using (MemoryStream memStr = new MemoryStream())
{memStr.Write(byteArray, 0, byteArray.Length);using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true)){string docText = null;using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())){docText = sr.ReadToEnd();}docText = docText.Replace("$Vender", "Microsoft");docText = docText.Replace("$Amount", "1234.56");docText = docText.Replace("$Today", DateTime.Today.ToShortDateString());using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))){sw.Write(docText);}
}
Console.WriteLine("Saving");
//save new file from stream memStr...

Run this code, we can find the result document content like this:

Purchasing Contract

Vender:Microsoft,

Description:bala bala~~~

Total Amount: 1234.56

Signature Date:2013/9/27

Use both the Word Automation Services and Open XML SDK, we can generate the word document by template and user data, and convert the result as a pdf file and save to another document library.

This my example code:

string siteUrl = "http://localhost";
using (SPSite spSite = new SPSite(siteUrl))
{//Querying for Template.docxSPList list = spSite.RootWeb.GetList("http://localhost/Shared%20Documents");SPQuery query = new SPQuery();query.ViewFields = @"<FieldRef Name='FileLeafRef' />";query.Query =@"<Where>
<Eq>
<FieldRef Name='FileLeafRef' />
<Value Type='Text'>Template.docx</Value>
</Eq>
</Where>";SPListItemCollection collection = list.GetItems(query);if (collection.Count != 1){Console.WriteLine("Test.docx not found");Environment.Exit(0);}Console.WriteLine("Opening");SPFile file = collection[0].File;byte[] byteArray = file.OpenBinary();using (MemoryStream memStr = new MemoryStream()){memStr.Write(byteArray, 0, byteArray.Length);using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true)){string docText = null;using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())){docText = sr.ReadToEnd();}docText = docText.Replace("$Vender", "Microsoft");docText = docText.Replace("$Amount", "1234.56");docText = docText.Replace("$Today", DateTime.Today.ToShortDateString());using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))){sw.Write(docText);}}Console.WriteLine("Saving");string newDocName = "MicrosoftContract.docx";file.ParentFolder.Files.Add(newDocName, memStr, true);Console.WriteLine("Starting conversion job");string wordAutomationServiceName = "Word Automation Services";ConversionJob job = new ConversionJob(wordAutomationServiceName);job.UserToken = spSite.UserToken;job.Settings.UpdateFields = true;job.Settings.OutputFormat = SaveFormat.PDF;job.AddFile(siteUrl + "/Shared%20Documents/"+newDocName,siteUrl + "/Docs/MicrosoftContract.pdf");job.Start();}
}

转载于:https://www.cnblogs.com/studyzy/p/3343211.html

User Word Automation Services and Open XML SDK to generate word files in SharePoint2010相关推荐

  1. C# : 操作Word文件的API - (将C# source中的xml注释转换成word文档)

    这篇博客将要讨论的是关于: 如何从C#的source以及注释, 生成一份Word格式的关于各个类,函数以及成员变量的说明文档. 他的大背景如下...... 最近的一个项目使用C#, 分N个模块, 在项 ...

  2. xml文件怎么转换成wps_xml文件转word文档 怎么将XML文档转成WORD文档

    1.找到需要转换为word文档的xml文档. 2.选择文档并点击鼠标右键,选择"打开方式"栏目中的"WPS表格"(或者excel表格),点击确定按钮. 3.点击 ...

  3. C# 添加Word水印(基于Spire.Cloud.SDK for .NET )

    概述 Spire.Cloud.SDK for .NET 提供了watermarksApi接口可用于添加水印,包括添加文本水印(SetTextWatermark).图片水印(SetImageWaterm ...

  4. java word合并单元格_java使用freemarker模板导出word(带有合并单元格)文档

    前言:最近要做一个导出word功能,其实网上有很多的例子,但是我需要的是合并单元格的,可是查了好久都没有自己想要的.研究了几天其实挺简单的,在这儿我就简单的介绍一下吧!(此方法只是一种思路,借鉴者还有 ...

  5. Java分布式中文分词组件 - word分词(转自 https //github com/ysc/word)

    首先给大家分享一个巨牛巨牛的人工智能教程,是我无意中发现的.教程不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵段子,像看小说一样,哈哈-我正在学习中,觉得太牛了,所以分享给大家!点这里可以跳转 ...

  6. 布局文件:报警告 This inspection highlights unknown XML attributes in Android resource files and Andro...

    新创建的项目,布局文件报警告: This inspection highlights unknown XML attributes in Android resource files and Andr ...

  7. Java准确获取Word/Excel/PPT/PDF的页数(附Word页数读不准的处理办法)

    Java准确获取Word/Excel/PPT/PDF的页数(附Word页数读不准的处理办法) 1.需求背景 2.环境准备工作 2.1 JACOB介绍及安装 2.2 Microsoft Office W ...

  8. Java读写word带样式,java将html导出带样式word文档

    java怎么由html生成word,保留html样式 @RequestMapping("download")public void exportWord( HttpServletRequest req ...

  9. [转载]Word直接发布新浪博客(以Word 2013为例)

    2019独角兽企业重金招聘Python工程师标准>>> 原文地址:Word直接发布新浪博客(以Word 2013为例) 作者:paulke2011 注意:这篇博客直接由Word 20 ...

最新文章

  1. 关于Canvas的一些经验
  2. SAP RETAIL 特性树(Characteristic Tree)的定义
  3. Cheat—— 给Linux初学者和管理员一个终极命令行备忘单
  4. Windows server 2003下Oracle10g安装图解
  5. asp.net中将数据库绑定到DataList控件的实现方法与实例代码
  6. 《IPv6技术精要》一2.4 扩展报头
  7. 动态规划训练25 [Food Delivery ZOJ - 3469 ]好题
  8. 虚拟服务器 端口管理,Apache服务配置虚拟主机(基于域名、端口、IP地址)与简单访问权限管理...
  9. 不同类型的变量与零值比较的方法
  10. Linux复制指定目录及子目录下特定类型的文件
  11. Python中列表的增、删、改、查、排序
  12. 将Office2010版EXCEL文件保存为2007版.XLS文件格式体积巨增解决方法
  13. 《UNIX环境高级编程——APUE》
  14. 支付业务与技术架构学习总结(1)——完整的支付系统整体架构
  15. Rayman的绝顶之路——Leetcode每日一题打卡14
  16. SAP 财务替代(基本内容及常用财务替代配置涉及退出提供源代码)
  17. 解决sysman.mgmt_task_qtable ORA-600 kdsgrp1错误
  18. android模拟量输入引脚,plc模拟量输入接线方法
  19. 轻开B2C电子商务网站(20141231版)发布手册
  20. matlab mcr安装图标,MCR 安装文档--matlab 2010b

热门文章

  1. java中与接口类,Java中类与类、类与接口、接口与接口的关系
  2. Golang实践录:命令行cobra库实例
  3. Oracle典型应用场景--数据迁移到本地测试
  4. 【kerberos】kerberos 认证 详情介绍
  5. 【Java】为什么java构造函数的构造器只能在第一行写this() 或者super() ?
  6. 【Flink】flink Kafka报错 : Failed to send data to Kafka: This server is not the leader for that topic-pa
  7. 87-Spark推测执行spark.speculation
  8. 【Docker】 Docker pull的时候指定仓库
  9. 记一次极其坑爹的Maven无法下载相关Jar包的问题:IDEA问题
  10. 12-Java读写CSV格式文件(opencsv)