Export SharePoint 2013 List Items to Word Document using SharePoint Server Side Object Model

Export SharePoint 2013 List Items to Word Document using SharePoint Server Side Object Model

In this post, we will discuss how we can export SharePoint 2013 list items to word document using SharePoint 2013 server object model. Here I have a SharePoint 2013 list which has few list items. My requirement is to export all items to a word document.


If you want to export to excel then you can follow, Export selected record to excel in SharePoint 2013 using JavaScript client object model and SPServices.

You can also check out:
Get Current User Details in InfoPath form using JavaScript and jQuery Client Object model SharePoint 2013

SharePoint Server 2016 Installation Step by Step

Deploy SharePoint 2013 designer workflow to a different site in SharePoint 2013

I have written the code in a button click inside a visual web part. Below is the code (on button click).

SPSite oSiteCollection = SPContext.Current.Site;
SPWeb web = oSiteCollection.RootWeb;

SPList oList = web.Lists.TryGetList(“Employee”);

SPListItemCollection collListItems = oList.Items;

HttpContext.Current.Response.Clear();

HttpContext.Current.Response.Charset = “”;

HttpContext.Current.Response.ContentType = “application/msword”;

string strFileName = “EmployeeList” + “.doc”;

HttpContext.Current.Response.AddHeader(“Content-Disposition”, “inline;filename=” + strFileName);

StringBuilder strHTMLContent = new StringBuilder();

strHTMLContent.Append(“<table>”.ToString());

foreach (SPListItem oListItem in collListItems)

{

strHTMLContent.Append(“<tr><td>” + oListItem[“Title”].ToString() + “</td></tr>”);

}

strHTMLContent.Append(“</table>”.ToString());

HttpContext.Current.Response.Write(strHTMLContent);

HttpContext.Current.Response.End();

HttpContext.Current.Response.Flush();

Once you deploy the Visual web part and then click on the button the file will be downloaded and will ask to Save. Now if you will open the word you will see the records like below:

Export SharePoint 2013 List Items to Word Document using SharePoint Server Side Object Model
Export SharePoint 2013 List Items to Word Document using SharePoint Server Side Object Model


Hope this article will be helpful.

Check out Best Alternative to InfoPath -> Try Now

You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →