将HTML编辑器内容保存到C#中的内容类型.DOCX

时间:2014-07-01 04:01:28

标签: c# asp.net .net

 private void ConvertHTMLtoDOCX(string txtcode)
 {
     System.Text.StringBuilder strBody = new System.Text.StringBuilder("");

     strBody.Append("<html " + "xmlns:o='urn:schemas-microsoft-com:office:office' " + "xmlns:w='urn:schemas-microsoft-com:office:word'" + "xmlns='http://www.w3.org/TR/REC-html40'>" + "<head><title>Time</title>");

     //The setting specifies document's view after it is downloaded as Print
     //instead of the default Web Layout
     strBody.Append("<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->");


     strBody.Append("<style>" + "<!-- /* Style Definitions */" + "@page Section1" + "   {size:8.5in 11.0in; " + "   margin:1.0in 1.25in 1.0in 1.25in ; " + "   mso-header-margin:.5in; " + "   mso-footer-margin:.5in; mso-paper-source:0;}" + " div.Section1" + "   {page:Section1;}" + "-->" + "</style></head>");

     strBody.Append("<body lang=EN-US style='tab-interval:.5in'>" + "<div class=Section1>" + Html_editor.Content + "</div></body></html>");

     //Force this content to be downloaded 
     //as a Word document with the name of your choice


     string FullFilePath = @"C:\Users\ravikant\Desktop\AR GitHub\07-05-2014\FinalTestARGithub\LetterTemplate\"+ txtcode+ ".docx"; 

     FileInfo file = new FileInfo(FullFilePath);
     if (file.Exists)
     {
        ClientScript.RegisterStartupScript(this.GetType(), "disExp", "<script>alert('File Already Exists');</script>");
     }
     else
     {
         Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
         Response.AppendHeader("Content-disposition", "inline; filename="+txtcode+".docx");
         Response.Write(strBody);
     }       
 }

以下是使用CONTENT-TYPE for .DOCX“application / vnd.openxmlformats-officedocument.wordprocessingml.document”的代码,打开文件时内容已损坏。

1 个答案:

答案 0 :(得分:1)

尝试此操作以了解文件的内容。

我用本机词.docx完成了这个,但不是以这种方式生成的.docx,所以它可能有效,也可能无效。

  1. 制作已保存文件的副本,将其扩展名从.docx更改为.zip。
  2. 试试并打开它。我们正在尝试找到一个文件document.xml,它通常位于“word”文件夹中。
  3. 在文本编辑器中打开它,查看是否有任何错误或者尝试通过XML验证器。 VisualStudio应该足以显示任何格式错误。
  4. 可能有用的在线XML验证器:http://www.xmlvalidation.com/

    以下几行也是可疑的:

    strBody.Append("<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->");
    

    因为我不确定单词将如何处理IE条件评论。注释掉或删除此行,看看会发生什么。

    strBody.Append("<style>" + "<!-- /* Style Definitions */" + "@page Section1" + "   {size:8.5in 11.0in; " + "   margin:1.0in 1.25in 1.0in 1.25in ; " + "   mso-header-margin:.5in; " + "   mso-footer-margin:.5in; mso-paper-source:0;}" + " div.Section1" + "   {page:Section1;}" + "-->" + "</style></head>");
    

    由于嵌套评论。 <!-- /* */-->。也许尝试将其更改为:strBody.Append("</head>");并查看是否有效。