使用 Sharepoint Word Automation 进行文本替换

2024-03-07

我正在使用 sharepoint 2010,我想做的是采用一个 word 文档模板,对几个关键字进行替换(例如:替换##ClientID##与客户端的 ID)并以特定名称将其保存在共享点上的库中。

我已经弄清楚如何使用 word interop 在本地计算机上执行此操作,但是 word interop 库并不是设计为作为服务运行的。然后我发现文字自动化服务 http://msdn.microsoft.com/en-us/library/ee559408.aspx这似乎做了我需要做的事情。然而,我在互联网上找到的每个例子(包括这里的SO)只是“如何从word文档转换为xxx”,使用Microsoft.Office.Word.Server.Conversions命名空间。我还没有找到有关如何使用的示例Microsoft.Office.Word.Server.Service命名空间来对文档进行查找和替换。 MSDN 非常缺乏如何使用这些类,我不知道从哪里开始使用它。

难道就不能使用这些服务来做我想做的事吗?如果可以做到,有人可以指出我正确的方向去做我想做的事吗?


看来 Word Automation Services 不是我想要用来做我想做的事情的,我需要的是开放 XML SDK http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx.

更新: 这是有关如何在文档中进行替换的代码,在我的文本中我想替换富文本框中的位置。这就是我在 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);
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Sharepoint Word Automation 进行文本替换 的相关文章

随机推荐