Búsqueda de sitios web

SharePoint Online: Importe un archivo CSV a la lista de SharePoint usando PowerShell


Escenario: ¡Mi requisito es importar datos de un archivo CSV a la lista de SharePoint Online desde una unidad local todos los días!

Cree una lista en SharePoint Online, que coincida con las columnas del archivo CSV, antes de ejecutar el script. Los nombres de las columnas en el CSV deben coincidir con los nombres internos de las columnas en la lista de SharePoint Online.

¿Tiene un archivo CSV que necesita importar a una lista de SharePoint Online? Bueno, ¡PowerShell lo hace fácil! En esta publicación, le mostraré cómo importar un archivo CSV a una lista de SharePoint Online usando PowerShell. Podrás importar cualquier tipo de datos a tu lista, incluidos texto, números y fechas. ¡Empecemos!

Secuencia de comandos de PowerShell para importar elementos de la lista de SharePoint desde un archivo CSV:

Si bien es posible copiar y pegar los datos de un archivo CSV en la lista de SharePoint Online usando la vista "Edición rápida", el enfoque de PowerShell es necesario para la automatización. Aquí está SharePoint Online PowerShell para importar CSV a la lista.


#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="Contacts"
$ImportFile ="c:\Scripts\EmpData.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 the Data from CSV and Add to SharePoint List
$data = Import-Csv $ImportFile
Foreach ($row in $data) {
    #add item to List
    $ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
    $Item = $List.AddItem($ListItemInfo)
    $Item["FirstName"] = $row.FirstName
    $Item["LastName"] = $row.LastName
    $Item["Department"] = $row.Department
    $Item["Mobile"] = $row.Mobile
    $Item.Update()
    $Context.ExecuteQuery() 
   
}
Write-host "CSV data Imported to SharePoint List Successfully!"

Esto importa CSV a la lista de SharePoint Online mediante PowerShell.

PnP PowerShell para importar datos de archivos CSV a la lista de SharePoint Online

Importemos CSV a la lista de SharePoint Online con PnP PowerShell con la ayuda de los cmdlets Import-CSV y Add-PnPListItem:


#Parameters
$SiteUrl = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Contacts"
$CSVPath = "C:\temp\Contacts.csv"

#Get he CSV file contents
$CSVData = Import-CSV -Path $CSVPath

#Connect to site
Connect-PnPOnline $SiteUrl -Interactive

#Iterate through each Row in the CSV and import data to SharePoint Online List
ForEach ($Row in $CSVData)
{
    Write-Host "Adding Contact $($Row.FirstName)"
    
    #Add List Items - Map with Internal Names of the Fields!
    Add-PnPListItem -List $ListName -Values @{"FirstName" = $($Row.FirstName); 
                            "LastName" = $($Row.LastName);
                            "Department"=$($Row.Department);
                            "Mobile" = $($Row.Mobile);
    };
}

Aquí está mi archivo CSV, que puedes descargar:

Y los datos importados en la lista:

Este PowerShell agrega nuevos elementos del archivo CSV proporcionado a la lista de SharePoint Online. Si desea actualizar la lista de SharePoint Online desde un archivo CSV, use: PowerShell para actualizar la lista de SharePoint Online desde CSV

Agregar elementos de lista de forma masiva a SharePoint Online desde un archivo CSV usando PnP PowerShell

Los scripts anteriores funcionan bien para tipos de campos simples, como líneas de texto individuales, opciones, etc. ¿Qué sucede si tiene tipos de campos complejos como Búsqueda, Selector de personas, etc.? Aquí está mi lista de "Proyectos" con casi todos los tipos de campos disponibles en SharePoint Online:

Estructura de la lista:

Aquí está el script de PowerShell actualizado para importar de forma masiva elementos de lista desde un CSV.


#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/projects"
$ListName = "Projects"
$CSVFilePath = "C:\Temp\ProjectData.csv"

#Function to get Lookup ID from Lookup Value
Function Get-LookupID($ListName, $LookupFieldName, $LookupValue)
{
    #Get Parent Lookup List and Field from Child Lookup Field's Schema XML
    $LookupField =  Get-PnPField -List $ListName -Identity $LookupFieldName
    [Xml]$Schema = $LookupField.SchemaXml
    $ParentListID = $Schema.Field.Attributes["List"].'#text'
    $ParentField  = $Schema.field.Attributes["ShowField"].'#text'
    $ParentLookupItem  = Get-PnPListItem -List $ParentListID -Fields $ParentField | Where {$_[$ParentField] -eq $LookupValue} | Select -First 1 
    If($ParentLookupItem -ne $Null)  { Return $ParentLookupItem["ID"] }  Else  { Return $Null }
}

Try {
    #Connect to the Site
    Connect-PnPOnline -URL $SiteURL -Interactive

    #Get the data from CSV file
    $CSVData = Import-CSV $CSVFilePath

    #Get the List to Add Items
    $List = Get-PnPList -Identity $ListName
    
    #Get fields to Update from the List - Skip Read only, hidden fields, content type and attachments
    $ListFields = Get-PnPField -List $ListName | Where { (-Not ($_.ReadOnlyField)) -and (-Not ($_.Hidden)) -and ($_.InternalName -ne  "ContentType") -and ($_.InternalName -ne  "Attachments") }
     
    #Loop through each Row in the CSV file and update the matching list item ID
    ForEach($Row in $CSVData)
    {
        #Frame the List Item to update
        $ItemValue = @{}            
        $CSVFields = $Row | Get-Member -MemberType NoteProperty | Select -ExpandProperty Name
        #Map each field from CSV to target list
        Foreach($CSVField in $CSVFields)
        {
            $MappedField = $ListFields | Where {$_.InternalName -eq $CSVField}
            If($MappedField -ne $Null)
            {
                $FieldName = $MappedField.InternalName
                #Check if the Field value is not Null
                If($Row.$CSVField -ne $Null)
                {
                    #Handle Special Fields
                    $FieldType  = $MappedField.TypeAsString 
                    If($FieldType -eq "User" -or $FieldType -eq "UserMulti") #People Picker Field
                    {
                        $PeoplePickerValues = $Row.$FieldName.Split(",")
                        $ItemValue.add($FieldName,$PeoplePickerValues)
                    }
                    ElseIf($FieldType -eq "Lookup" -or $FieldType -eq "LookupMulti") #Lookup Field
                    {
                        $LookupIDs = $Row.$FieldName.Split(",") | ForEach-Object { Get-LookupID -ListName $ListName -LookupFieldName $FieldName -LookupValue $_ }                
                        $ItemValue.Add($FieldName,$LookupIDs)
                    }
                    ElseIf($FieldType -eq "DateTime")
                    {
                        $ItemValue.Add($FieldName,[DateTime]$Row.$FieldName)
                    }
                    Else
                    {
                        #Get Source Field Value and add to Hashtable
                        $ItemValue.Add($FieldName,$Row.$FieldName)
                    }
                }
            }
        }
        Write-host "Adding List item with values:"
        $ItemValue | Format-Table
        #Add New List Item
        Add-PnPListItem -List $ListName -Values $ItemValue | Out-Null
    }
}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Asegúrese de que los datos en el CSV estén en el formato correcto y que el archivo CSV tenga nombres internos de campos de lista como columnas. Puede descargar el archivo CSV desde:

¿Qué tal importar un archivo Excel (en lugar de CSV) a la lista de SharePoint Online? Claro, aquí tienes: Importa Excel a la lista de SharePoint Online usando PowerShell

Artículos relacionados