2011-11-28 84 views
2

我希望能够在Sharepoint中存储模板word文档,并将其用作吐出包含注入到模板中的数据的word文档的基础。从sharepoint打开word文档,替换文本和流到用户

我可以使用代码如下得到我的Word文档的文本:

SPSite sc = SPContext.Current.Site; 
    SPWeb web = sc.AllWebs["MySite"];    

    string contents = web.GetFileAsString("Documents/MyTemplateWord.doc"); 

    web.Dispose(); 

然后,我可以串在“内容”变量替换。这工作正常。

我现在想“打开”这个新的内容作为word文档。

我给这家代码如下:

string attachment = "attachment; filename=MyWord.doc"; 
    HttpContext.Current.Response.Clear(); 
    HttpContext.Current.Response.ClearHeaders(); 
    HttpContext.Current.Response.ClearContent(); 
    HttpContext.Current.Response.AddHeader("content-disposition", attachment); 
    HttpContext.Current.Response.ContentType = "text/ms-word"; 
    HttpContext.Current.Response.Write(outputText); 
    HttpContext.Current.Response.End(); 

我得到一个错误,虽然,不知道如何解决它。

错误:Sys.WebForms.PageRequestManagerParserErrorException:无法解析从服务器收到的消息。此错误的常见原因是,通过调用Response.Write(),响应筛选器,HttpModules或服务器跟踪已启用来修改响应时。详细信息:错误解析'ࡱ>

现在很明显,它有解析“字符串”内容的问题。

我在做什么错?有没有不同的方式我应该这样做?

回答

1

您不读取字符串,而是将二进制数据转换为字符串。 (请注意,docx是包含xml数据的zip文件)。 您在这方面的替换文本方法的性质是有缺陷的。

如果不是因为要查找/替换文本的愿望,我会建议

using(SPWeb web = new SPSite("<Site URL>").OpenWeb()) 
{ 
    SPFile file = web.GetFile("<URL for the file>"); 
    byte[] content = file.OpenBinary(); 
    HttpContext.Current.Response.Write(content); 
} 

http://support.microsoft.com/kb/929265 使用的BinaryWrite将数据获取到您的网页。

但是,由于您使用的是Word,我建议将文档加载到Microsoft.Office.Interop.Word objects的实例中。 但是,使用Word interop可能会有点时间吸血鬼。

0

1-加载DOCX组件使用Novacode您shaepoint包https://docx.codeplex.com

2-;

3-注意以下样本下载按钮

protected void ButtonExportToWord_Click(object sender, EventArgs e) 
     { 
      byte[] bytesInStream; 

      using (Stream tplStream = 
       SPContext.Current.Web.GetFile("/sitename/SiteAssets/word_TEMPLATE.docx").OpenBinaryStream()) 
      { 
       using (MemoryStream ms = new MemoryStream((int)tplStream.Length)) 
       { 
        CopyStream(tplStream, ms); 
        ms.Position = 0L; 

        DocX doc = DocX.Load(ms); 
        ReplaceTextProxy(doc,"#INC#", "11111111"); 

        doc.InsertParagraph("This is my test paragraph"); 

        doc.Save(); 
        bytesInStream = ms.ToArray(); 
       } 
      } 

      Page.Response.Clear(); 
      Page.Response.AddHeader("Content-Disposition", "attachment; filename=" + 
       CurrentFormId + ".docx"); 
      Page.Response.AddHeader("Content-Length", bytesInStream.ToString()); 
      Page.Response.ContentType = "Application/msword"; 
      Page.Response.BinaryWrite(bytesInStream); 

      Page.Response.Flush(); 
      Page.Response.Close(); 
      //Page.Response.End();// it throws an error 
     } 

     private void ReplaceTextProxy(DocX doc, string oldvalue, string newValue) 
     { 
      doc.ReplaceText(oldvalue,newValue,false, RegexOptions.None, null, null, 
         MatchFormattingOptions.SubsetMatch); 
     }