Generate a Word document from list data

Posted by PeterBrunone on ASP.net Weblogs See other posts from ASP.net Weblogs or by PeterBrunone
Published on Mon, 06 Dec 2010 16:24:00 GMT Indexed on 2010/12/06 16:57 UTC
Read the original article Hit count: 266

Filed under:
|
|
|

This came up on a discussion list lately, so I threw together some code to meet the need.  In short, a colleague needed to take the results of an InfoPath form survey and give them to the user in Word format.  The form data was already in a list item, so it was a simple matter of using the SharePoint API to get the list item, formatting the data appropriately, and using response headers to make the client machine treat the response as MS Word content. 

The following rudimentary code can be run in an ASPX (or an assembly) in the 12 hive.  When you link to the page, send the list name and item ID in the querystring and use them to grab the appropriate data.

// Clear the current response headers and set them up to look like a word doc.
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset ="";
HttpContext.Current.Response.ContentType ="application/msword";
string strFileName = "ThatWordFileYouWanted"+ ".doc";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);

// Using the current site, get the List by name and then the Item by ID (from the URL).
string myListName = HttpContext.Current.Request.Querystring["listName"];
int myID = Convert.ToInt32(HttpContext.Current.Request.Querystring["itemID"]);
SPSite oSite = SPContext.Current.Site;
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.Lists["MyListName"];
SPListItem oListItem = oList.Items.GetItemById(myID);

// Build a string with the data -- format it with HTML if you like.
StringBuilder strHTMLContent = newStringBuilder();

// *
// Here's where you pull individual fields out of the list item.
// *

// Once everything is ready, spit it out to the client machine.

HttpContext.Current.Response.Write(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();

© ASP.net Weblogs or respective owner

Related posts about sharepoint

Related posts about ASP.NET