How to Export Web parts in SharePoint 2013?
In this blog, we will see the piece of the code to export the web part in a web part page. A SharePoint Web part is a piece of server code which does the certain functionality like listing your site assets. A SharePoint web part can be dragged and dropped into any Web Part Zone. Here is the piece of code to achieve the functionality of exporting it.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
foreach (string Title in webPartTitles)
{
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in wpManager.WebParts)
{
// Find the matched closed web part in WebParts collection
if (webPart.Title == Title && webPart.IsClosed == true)
{
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
webPart.ExportMode = WebPartExportMode.All;
// Export the closed webpart to a memory stream.
wpManager.ExportWebPart(webPart, writer);
writer.Flush();
stream.Position = 0;
XmlTextReader reader = new XmlTextReader(stream);
// Import the exported webpart.
System.Web.UI.WebControls.WebParts.WebPart newWebPart = wpManager.ImportWebPart(reader, out errorMessage);
reader.Close();
writer.Close();
// Show the imported webpart.
panel.Controls.Add(newWebPart);
break;
}
}
}
In this code, make sure that your Webpart export mode is set to all. By Default it is set to None. Happy SharePointing Folks 🙂