使用SharePoint的Word自动化做的文本替换 [英] Using Sharepoint Word Automation to do a text replace

查看:195
本文介绍了使用SharePoint的Word自动化做的文本替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与SharePoint 2010的工作,我所要做的是采取一个Word文档模板,做一次替换几个关键词(例如:更换 ##的ClientID ## 与客户的ID),并将其保存在在SharePoint库中的特定名称。

I am working with sharepoint 2010, what I am trying to do is take a word document template, do a replace on a few key words (ex: replace ##ClientID## with the id of the client) and save it with a specific name in a library on sharepoint.

我已经找到了如何做到这一点的本地计算机上的字互操作,但是这个词互操作库的目的不是要被作为服务运行。后来我发现字自动化服务这似乎做什么,我需要做的。但是每一个例子,我在互联网上找到(包括这里SO)仅仅是如何从Word文档转换为XXX使用 Microsoft.Office.Word.Server.Conversions 命名空间。我还没有找到如何使用 Microsoft.Office.Word.Server.Service 命名空间做了查找和替换文档中的例子。在MSDN非常缺乏关于如何使用这些类,我不知道从哪里开始使用它。

I have figured out how to do this on a local computer with word interop, however the word interop library is not designed to be run as a service. I then discovered Word Automation Services which appear to do what I need to do. However every example I find on the internet (including here on SO) is just "How to convert from a word document to xxx" using the Microsoft.Office.Word.Server.Conversions namespace. I have yet to find a example on how to use the Microsoft.Office.Word.Server.Service namespace to do a find and replace on a document. The MSDN is very lacking on how to use the classes and I do not know where to begin using it.

这难道不是可以使用的服务,做我想做什么?如果这是可以做到可有人点我在正确的方向做我想做的事?

Is it not possible to use the services to do what I want to? If it can be done can someone point me in the right direction to do what I want to do?

推荐答案

看来,字自动化服务是不是我想用做我想做的事情,我需要的是的打开XML SDK

It appears that Word Automation Services is not what I want to use to do what I want to do, what I need is Open XML SDK.

更新: 下面教你如何做一个替换文件的code,在我的文字,我想在富文本框,以取代在那里。所以这就是为什么我找里面SdtRun。

UPDATE: here is the code on how to do a replace on the document, in my the text I wanted to replace where in rich text boxes. so that is why I am looking inside SdtRun.

public FileDetails GetOrGenerateChecklist(string PracticeName, string ContractID, string EducationDate, string MainContactInfo, string Address)
{
    if (String.IsNullOrEmpty(PracticeName) || String.IsNullOrEmpty(ContractID))
        return null;
    SPWeb web = SPContext.Current.Web;

    SPDocumentLibrary list = (SPDocumentLibrary)web.Lists["Educator Checklists"];
    var templetAddr = String.Concat(web.Url, '/', list.DocumentTemplateUrl);
    SPQuery query = new SPQuery();
    query.Query = string.Concat(
                            "<Where><Eq>",
                                "<FieldRef Name='FileLeafRef'/>",
                                "<Value Type='File'>", PracticeName, " - ", ContractID, ".docx</Value>",
                            "</Eq></Where>");
    var items = list.GetItems(query);

    //if document exists return existing document.
    if (items.Count > 0)
        return new FileDetails() { Address = String.Concat(web.Url, "/Educator Checklists/", PracticeName, " - ", ContractID, ".docx"), LastModified = (DateTime)items[0]["Modified"]};

    //Begin transforming form template to document.
    MemoryStream documentStream;

    //copy the stream to memory
    using (Stream tplStream = web.GetFile(templetAddr).OpenBinaryStream())
    {
        documentStream = new MemoryStream((int)tplStream.Length);
        CopyStream(tplStream, documentStream);
        documentStream.Position = 0L;
    }

    using (WordprocessingDocument template = WordprocessingDocument.Open(documentStream, true))
    {
        template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
        MainDocumentPart mainPart = template.MainDocumentPart;
        mainPart.DocumentSettingsPart.AddExternalRelationship(
            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
            new Uri(templetAddr, UriKind.Absolute));

        ReplaceText(mainPart, "#PracticeName#", PracticeName);
        if(!String.IsNullOrEmpty(EducationDate))
            ReplaceText(mainPart, "#EducationDate#", EducationDate);
        if(!String.IsNullOrEmpty(MainContactInfo))
            ReplaceText(mainPart, "#MainContactInfo#", MainContactInfo);
        if(!String.IsNullOrEmpty(Address))
            ReplaceText(mainPart, "#Address#", Address);
    }
    documentStream.Position = 0L;
    try
    {
        list.RootFolder.Files.Add(String.Concat(PracticeName, " - ", ContractID, ".docx"), documentStream);
    }
    catch(SPException)
    {
        return null;
    }

    return new FileDetails() { Address = String.Concat(web.Url, "/Educator Checklists/", PracticeName, " - ", ContractID, ".docx"), LastModified = DateTime.Now };


}

private static void CopyStream(Stream source, Stream destination, int bufferSize = 0x1000)
{
    int num;
    byte[] buffer = new byte[bufferSize];
    while ((num = source.Read(buffer, 0, buffer.Length)) != 0)
    {
        destination.Write(buffer, 0, num);
    }

}

private static void ReplaceText(MainDocumentPart docPart, string match, string value)
{
    if (value == null)
        value = String.Empty;
    var sdtr = docPart.Document.Descendants<SdtRun>();
    foreach (var sdt in sdtr)
    {
        if (sdt.InnerText == match)
        {

            Text txt = new Text(value);
            //using the sdt.FirstChild.FirstChild.CloneNode(true) will copy the text formatting of the old text.
            var newtext = new SdtContentRun(new Run(sdt.FirstChild.FirstChild.CloneNode(true), txt));
            sdt.SdtContentRun.RemoveAllChildren();
            sdt.SdtContentRun.InsertAt(newtext, 0);
        }
    }
}

这篇关于使用SharePoint的Word自动化做的文本替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆