Monday, August 26, 2013

Add Excel Web Access WebPart Using PowerShell


Use Add-EWAWebPart function to add a Excel Web Access webpart in a SharePoint page using PowerShell script.

Parameters : 
  1. $webUrl - Mandatory - SharePoint Web Url - e.g. http://server:port/ 
  2. $ExcelFileURL - Mandatory - Excel File URL 
  3. $pageRelativeUrl - Mandatory - SharePoint WebPart Page Relative Url , e.g. "Library/page.aspx"
  4. $zone - MandatoryThe WebPartZoneBase that webPart is being added to.e.g. Left, Right
  5. $zoneIndex - Mandatory - An integer that represents the ordinal position that webPart occupies in zone, relative to other controls in zone.
function Add-EWAWebPart
{   
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]$webUrl,
    [Parameter(Mandatory=$true)]
    [string]
$ExcelFileURL,
    [Parameter(Mandatory=$true)]
    [string]
$pageRelativeUrl,
    [Parameter(Mandatory=$true)]
    [string]
$
zone,
     [Parameter(Mandatory=$true)]
    [int]
$
zoneIndex
)     
  
    Start-SPAssignment -Global 

    $spWeb = Get-SPWeb -Identity $webUrl
   
    $newXml = "<?xml version='1.0' encoding='utf-8'?><webParts><webPart xmlns='http://schemas.microsoft.com/WebPart/v3'><metaData><type name='Microsoft.Office.Excel.WebUI.ExcelWebRenderer, Microsoft.Office.Excel.WebUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' /><importErrorMessage>Cannot import this Web Part.</importErrorMessage></metaData><data><properties><property name='Title' type='string'>EWAWP</property><property name='WorkbookUri' type='string'>"+ $ExcelFileURL +"</property></properties></data></webPart></webParts>"
   
    $webpartmanager=$spWeb.GetLimitedWebPartManager($pageRelativeUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
    $errorMsg =""
    $sr = new-object System.IO.StringReader $newXml
    $xr = new-object System.Xml.XmlTextReader $sr
    $myCustomWP = $webpartmanager.ImportWebPart($xr,[ref]$errorMsg)  
        
    if(!$webpartmanager.WebParts.Contains($myCustomWP))
    {
        Write-Host -NoNewLine -f yellow "Adding Webpart - $($myCustomWP.title)"       
        $webpartmanager.AddWebPart($myCustomWP, $zone, $zoneIndex)
        write-host -f Green "...Success!"
    }

    Stop-SPAssignment -Global 


}



Function  Calling -

$webUrl = "http://sever:port"
$ExcelFileURL = "http://sever:port/DocLib1/excel.xslx"
$pageRelativeUrl =  "DocLib1/abc.aspx"
$zone = "Left"
$zoneIndex = 1

Add-EWAWebPart $webUrl  $ExcelFileURL $pageRelativeUrl $zone $zoneIndex


No comments: