SharePoint Online: exportar elementos de la lista a CSV usando PowerShell
Requisito: Exportar elementos de la lista de SharePoint Online a un archivo CSV.
¿Cómo exportar elementos de la lista de SharePoint Online a Excel o CSV?
¿Necesita exportar datos de una lista de SharePoint Online a CSV? Es posible que desee exportar elementos de la lista de SharePoint Online a Excel o CSV por varios motivos. Por ejemplo, es posible que desee crear una copia de seguridad de sus datos. Es posible que deba migrar sus datos a otra plataforma o aplicación para su posterior análisis o manipulación. Cualquiera sea el motivo, Microsoft ha simplificado este proceso. Esta publicación de blog le mostrará cómo exportar elementos de lista de SharePoint Online a CSV usando PowerShell y la interfaz del navegador web. ¡Empecemos!
¿Cómo exporto una lista de SharePoint a CSV? Para exportar la lista de SharePoint Online a un archivo CSV, simplemente navegue hasta la lista y haga clic en "Exportar a CSV" en el menú "Exportar", y SharePoint exportará los datos de la lista a un archivo CSV. ¡Es así de simple!
Secuencia de comandos de PowerShell para exportar elementos de la lista de SharePoint a CSV
Aunque puedes exportar los datos de la lista a un archivo CSV manualmente, como se describe anteriormente, es posible que tengas que automatizar el proceso en algunas situaciones. Le mostraré cómo usar PowerShell para exportar elementos de la lista de SharePoint Online al formato CSV.
Así es como puede exportar la lista de SharePoint Online a CSV a través de PowerShell:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
##Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/poc"
$ListName="Employee"
$ExportFile ="c:\Scripts\ListRpt.csv"
$UserName="Salaudeen@crescent.com"
$Password ="Password goes here"
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Context.Credentials = $credentials
#Get the List
$List = $Context.web.Lists.GetByTitle($ListName)
#Get All List Items
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$ListItems = $List.GetItems($Query)
$context.Load($ListItems)
$context.ExecuteQuery()
#Array to Hold List Items
$ListItemCollection = @()
#Fetch each list item value to export to excel
$ListItems | foreach {
$ExportItem = New-Object PSObject
$ExportItem | Add-Member -MemberType NoteProperty -name "Title" -value $_["Title"]
$ExportItem | Add-Member -MemberType NoteProperty -Name "Department" -value $_["Department"]
#Add the object with the above properties to the Array
$ListItemCollection += $ExportItem
}
#Export the result Array to CSV file
$ListItemCollection | Export-CSV $ExportFile -NoTypeInformation
Write-host "List data Exported to CSV file successfully!"
Tenga en cuenta que este script obtiene todos los elementos de la lista de una lista, pero no obtiene de forma recursiva elementos de carpetas y subcarpetas (si tiene carpetas y subcarpetas). Para recuperar todos los elementos de la lista de forma recursiva, simplemente cambie la parte de la consulta CAML como:
#Get all List items from the library Including Items in Sub-Folder
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml="<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType'/><Value Type='Integer'>0</Value></Eq></Where></Query></View>"
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()
SharePoint Online PowerShell para exportar lista a CSV
Si bien el script anterior exporta las columnas seleccionadas al archivo de Excel, modifiquémoslo para exportar todos los datos de las columnas a Excel.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
##Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/"
$ListName= "Projects"
$ExportFile ="c:\ListItems.csv"
#Get Credentials to connect
$Cred = Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Ctx.Credentials = $Credentials
#Get the List
$List = $Ctx.web.Lists.GetByTitle($ListName)
#Get All List Items
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$ListItems = $List.GetItems($Query)
$FieldColl = $List.Fields
$Ctx.Load($ListItems)
$Ctx.Load($FieldColl)
$Ctx.ExecuteQuery()
#Array to Hold List Items
$ListItemCollection = @()
#Fetch each list item value to export to excel
Foreach($Item in $ListItems)
{
$ExportItem = New-Object PSObject
Foreach($Field in $FieldColl)
{
if($NULL -ne $Item[$Field.InternalName])
{
#Expand the value of Person or Lookup fields
$FieldType = $Item[$Field.InternalName].GetType().name
if (($FieldType -eq "FieldLookupValue") -or ($FieldType -eq "FieldUserValue"))
{
$FieldValue = $Item[$Field.InternalName].LookupValue
}
else
{
$FieldValue = $Item[$Field.InternalName]
}
}
$ExportItem | Add-Member -MemberType NoteProperty -name $Field.InternalName -value $FieldValue
}
#Add the object with above properties to the Array
$ListItemCollection += $ExportItem
}
#Export the result Array to CSV file
$ListItemCollection | Export-CSV $ExportFile -NoTypeInformation
Write-host "List data Exported to CSV file successfully!"
Y la salida:
Exportar listas más grandes de SharePoint Online a un archivo CSV
¿Qué pasa si su lista tiene más de 5000 elementos? ¿Qué tal obtener valores de campos especiales como MMS, búsqueda múltiple, URL, etc.?
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/PMO"
$ListName= "Projects"
$ExportFile ="C:\temp\Projects.csv"
$BatchSize = 500
#Get Credentials to connect
$Cred = Get-Credential
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the List
$List = $Ctx.web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
#Get All List Fields
$FieldColl = $List.Fields
$Ctx.Load($FieldColl)
$Ctx.ExecuteQuery()
#Filter List fields - Skip Read only, hidden fields, content type and attachments
$ListFields = $FieldColl | Where { (-Not ($_.ReadOnlyField)) -and (-Not ($_.Hidden)) -and ($_.InternalName -ne "ContentType") -and ($_.InternalName -ne "Attachments") }
#Define Query to get List Items in batch
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml = @"
<View Scope='RecursiveAll'>
<Query>
<OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
</Query>
<RowLimit Paged="TRUE">$BatchSize</RowLimit>
</View>
"@
#Array to Hold List Items
$ListItemCollection = @()
#Get List Items in Batch
Do
{
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()
#Fetch each list item value to export to excel
Foreach($Item in $ListItems)
{
$ExportItem = New-Object PSObject
Foreach($Field in $ListFields)
{
If($NULL -ne $Item[$Field.InternalName])
{
#Handle Special Fields
$FieldType = $Field.TypeAsString
If($FieldType -eq "User" -or $FieldType -eq "UserMulti" -or $FieldType -eq "Lookup" -or $FieldType -eq "LookupMulti")
{
$FieldValue = $Item[$Field.InternalName].LookupValue -join "; "
}
ElseIf($FieldType -eq "URL") #Hyperlink
{
$URL = $Item[$Field.InternalName].URL
$Description = $Item[$Field.InternalName].Description
$FieldValue = "$URL, $Description"
}
ElseIf($FieldType -eq "TaxonomyFieldType" -or $FieldType -eq "TaxonomyFieldTypeMulti") #MMS
{
$FieldValue = $Item[$Field.InternalName].Label -join "; "
}
Else
{
#Get Source Field Value
$FieldValue = $Item[$Field.InternalName]
}
}
$ExportItem | Add-Member -MemberType NoteProperty -name $Field.InternalName -value $FieldValue
}
#Add the object with above properties to the Array
$ListItemCollection += $ExportItem
}
$Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
}
While($Query.ListItemCollectionPosition -ne $null)
#Export the result Array to CSV file
$ListItemCollection | Export-CSV $ExportFile -NoTypeInformation
Write-host "List data Exported to CSV file successfully!"
Exportar elementos de lista de SharePoint Online a CSV usando PnP PowerShell
Para exportar la lista de SharePoint Online a CSV, utilice este script de PowerShell. Este script exporta valores de campo seleccionados de la lista proporcionada. Lo primero que debe hacer es conectarse a la URL de su sitio de SharePoint Online. Luego, obtenga todos los elementos de la lista de destino que desea exportar. Finalmente, ejecute el cmdlet Export-CSV y especifique la ruta donde desea exportar los datos de la lista de SharePoint a un archivo CSV. El cmdlet Export-Csv también tiene otros parámetros útiles como Agregar, Codificación, etc.
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/projects"
$ListName = "Projects"
$SelectedFields = @("ProjectName","Project_x0020_Manager", "StartDate")
$CSVPath = "C:\Temp\ListData.csv"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get List items from the list
$ListItems = Get-PnPListItem -List $ListName -Fields $SelectedFields -PageSize 500
#Iterate through each item and extract data
$ListDataColl = @()
$ListItems | ForEach-Object {
$ListData = New-Object PSObject
#Get the Field Values of the item as text
$ListItem = Get-PnPProperty -ClientObject $_ -Property FieldValuesAsText
ForEach($Field in $SelectedFields)
{
$ListData | Add-Member Noteproperty $Field $ListItem[$Field]
}
$ListDataColl += $ListData
}
#Export data to CSV
$ListDataColl
$ListDataColl | Export-CSV $CSVPath -NoTypeInformation
Esto exportará todos los elementos de la lista especificada a un archivo CSV llamado "ListData.csv" en la carpeta "C:\Temp" de su computadora. Luego puede abrir este archivo en Excel u otro programa de hoja de cálculo para ver los datos. Asegúrese de tener instalado el módulo PnP PowerShell antes de ejecutar este script.
¿Qué tal exportar todos los valores de campo disponibles desde una lista de SharePoint Online? Bueno, aquí está PnP PowerShell para exportar elementos de la lista en línea de SharePoint a CSV:
#Config Parameter
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Access Requests"
$CSVPath = "C:\Temp\ListData.csv"
$ListDataCollection= @()
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
$Counter = 0
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000
#Get all items from list
$ListItems | ForEach-Object {
$ListItem = Get-PnPProperty -ClientObject $_ -Property FieldValuesAsText
$ListRow = New-Object PSObject
$Counter++
Get-PnPField -List $ListName | ForEach-Object {
$ListRow | Add-Member -MemberType NoteProperty -name $_.InternalName -Value $ListItem[$_.InternalName]
}
Write-Progress -PercentComplete ($Counter / $($ListItems.Count) * 100) -Activity "Exporting List Items..." -Status "Exporting Item $Counter of $($ListItems.Count)"
$ListDataCollection += $ListRow
}
#Export the result Array to CSV file
$ListDataCollection | Export-CSV $CSVPath -NoTypeInformation -Encoding UTF8
Este script obtiene todos los elementos de la lista y los exporta a un archivo CSV. Si desea aplicar filtros a los elementos de la lista, digamos que desea obtener todos los elementos de la lista creados en los últimos 30 días, puede usar:
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 | ? { $_["Created"] -gt (Get-Date).AddDays(-30) }
Publicaciones relacionadas:
- SharePoint Online: Informe de usuarios y grupos del sitio mediante PowerShell
- Exportar elementos de lista a CSV en SharePoint Server usando PowerShell
- SharePoint Online: eliminación masiva de archivos de un CSV mediante PowerShell


