Monday, January 16, 2012

Export SharePoint List items to 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.Clear();
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("<br>".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>");
                                                           
}
strHTMLContent.Append("</table>".ToString());
strHTMLContent.Append("<br><br>".ToString());
HttpContext.Current.Response.Write(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();

No comments:

Post a Comment