Export SharePoint List items to Word Document

In this article I am showing you how to export list items in to word document. In SharePoint we have a default feature to export to Excel but there is no default feature to export to word. This article will help you to achieve the functionality.

First of all you can make use of the code to develop it as a web part or you can make it as a feature to deploy it to SharePoint so that it will come as a new menu item with list Actions. I am just explaining the code sample only so that you can make use of it where ever you want. We can select the fields from the list which we want to export to the word document.

//Opening the current site
SPSite oSiteCollection = SPContext.Current.Site; 

//Fetching the current list
SPList oList = oSiteCollection.AllWebs["Site_Name"].Lists["List_Name"];
SPListItemCollection collListItems = oList.Items;

//Creating HttpContext
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/msword";

//File name for the exported word document
string strFileName = "SampleDocument" + ".doc";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);

//Giving heading to the Word Document with style
StringBuilder strHTMLContent = new StringBuilder();
strHTMLContent.Append(" <h1 title='Heading' align='Center' style='font-family:verdana;font-size:80%;color:black'><u> EXPORT TO WORD SAMPLE </u></h1>".ToString());
strHTMLContent.Append("<table style=margin-top: 8px; border=1 bordercolor=#808080 frame=hsides rules=rows cellpadding=0 cellspacing=0 width=100%>".ToString());

//Looping through each list item in  the list
foreach (SPListItem oListItem in collListItems)
    strHTMLContent.Append("<tr><td>" + oListItem["Choice_Field_Name"].ToString() +"</td></tr>");

This will cause an Open / Save As dialog box to pop up with the filename SampleDocument.doc.

I have uploaded the sample code also so that you can make use I t in your application.