Saturday, November 23, 2013

creating word documents using open xml with asp.net

Now in this article i will explain how to use the Office Open XML C# (alternate solution to the Interop object. 

The Open XML provides you set of .NET API. It helps helps you manipulate and creating the documents in the Open XML Formats
in both the environments (i.e client and server both) and that is without help of MS office applications.

Before using Open XML Format, you have to add the below namespaces in your C# class. Add references to the Packaging and Spreadsheet API components with the following code.
 
 
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
 
Here is the CreateOpenXmlDocument function where you need to pass the filepath and it will created that doc file on specified positionl
 
public void CreateOpenXmlDocument(string filepath)
{
    
 using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
  {
    // Add a main document part.
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

    mainPart.Document = new Document();
    Body body = mainPart.Document.AppendChild(new Body());
    Paragraph para = body.AppendChild(new Paragraph());
    Run run = para.AppendChild(new Run());
    run.AppendChild(new Text("Create text sample text, coding stuffs daily..."));
  }
}



Here now i am integrating that function into my page_load event.


protected void Page_Load(object sender, EventArgs e)
{

      string FilePath =  @"C:\\Temp";
      CreateWordprocessingDocument(FilePath);

      FileInfo myDoc = new FileInfo(FilePath);
      Response.Clear();
      Response.ContentType = "Application/msword";
      Response.AddHeader("content-disposition", "attachment;filename=" + myDoc.Name);
      Response.AddHeader("Content-Length", myDoc.Length.ToString());
      Response.ContentType = "application/octet-stream";
      Response.WriteFile(myDoc.FullName);
      Response.End();

}
 
 
This is just an sample doc creation , you may even format the document with adding images, graphs, style to para and may more. Just refer this Microsoft article on how to do this. 

feel free to raise your suggestion/comments on this. Thanks you and happy coding....


 
 
 

1 comment:

  1. Can you add a header to the document that shows up on every page?

    ReplyDelete