0

Below is the code. What are the changes we need to do.

HttpContext context = HttpContext.Current;
    context.Response.Clear();
    context.Response.AppendHeader("content-disposition", "attachment;filename=" + strFileName + ".docx");
    context.Response.Charset = "";
    context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    var stringWriter = new StringWriter();
    stringWriter.Write(strContent);
    var htmlWriter = new HtmlTextWriter(stringWriter);
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
    HttpContext.Current.Response.Write(oHtmlTextWriter);
    context.Response.Write(stringWriter.ToString());
    context.Response.End();
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
Ganesh Atkale
  • 19
  • 1
  • 8
  • Can you explain what you expect to happen? The code you posted obviously is not going to work because you don't send a valid Open XML package file. Simply writing out HTML and naming it .docx is not going to convert HTML into a Word file. – Dirk Vollmar Nov 18 '16 at 12:10
  • Thanks Dirk For the reply. I am passing HTML code in strContent, writing on Doc file, so I am looking to download docx file with content. Could you please help on this? – Ganesh Atkale Nov 21 '16 at 05:02

1 Answers1

1

You can't simply write out HTML, give it a .docx file name extension and expect Word to correctly open that document. A .docx file needs to be a valid Office Open XML package, which basically is a zip container with various XML files in it (you can easily see that by renaming a .docx document to .zip and then open it using a standard zip tool).

What you can do now to fix the problem and get a valid Word file:

  • Instead of HTML, create a valid docx file using Microsoft's Open XML SDK. There a samples included with the SDK that show you how to create Word documents with it.
  • If you can't change from creating HTML you are also able to embed HTML into a Word document using a so-called altChunk. This is described in another answer here.
  • Depending on the content that you generate, there might also be the possibility to create a template Word document, where you only need to fill placeholder. Such a solution could e.g. be build around Content Controls and Custom XML. Then you only need to replace a single XML file in the docx package to fill your document. A basic tutorial for that is available here.
Community
  • 1
  • 1
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316