PAD: Automate filling in Word Template with data read from CSV
31 January, 2024
In this video I demonstrate how you can automate filling in a Microsoft Word Template with data read from a CSV File. We use Power Automate Desktop along with some PowerShell scripts.
PowerShell Script:
####UN-ZIP#####
param (
[string]$template
)
# unzip function
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip {
param([string]$zipfile, [string]$outpath)
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}
$Directory = Split-Path -Path $template -Parent
$tempFolder = $Directory + "\Populate-Word-DOCX"
Remove-Item $tempFolder -ErrorAction SilentlyContinue -Recurse -Confirm:$false | Out-Null
mkdir $tempFolder | Out-Null
Unzip $template $tempFolder
$tempFolder +"\word\document.xml"
#####ZIP######
param (
[string]$name
)
# unzip function
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Zip {
param([string]$folderInclude, [string]$outZip)
[System.IO.Compression.CompressionLevel]$compression = "Optimal"
$ziparchive = [System.IO.Compression.ZipFile]::Open( $outZip, "Update" )
# loop all child files
$realtiveTempFolder = (Resolve-Path $tempFolder -Relative).TrimStart(".\")
foreach ($file in (Get-ChildItem $folderInclude -Recurse)) {
# skip directories
if ($file.GetType().ToString() -ne "System.IO.DirectoryInfo") {
# relative path
$relpath = ""
if ($file.FullName) {
$relpath = (Resolve-Path $file.FullName -Relative)
}
if (!$relpath) {
$relpath = $file.Name
} else {
$relpath = $relpath.Replace($realtiveTempFolder, "")
$relpath = $relpath.TrimStart(".\").TrimStart("\\")
}
# display
Write-Host $relpath -Fore Green
Write-Host $file.FullName -Fore Yellow
# add file
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ziparchive, $file.FullName, $relpath, $compression) | Out-Null
}
}
$ziparchive.Dispose()
}
$Directory = Split-Path -Path $name -Parent
$tempFolder = $Directory + "\Populate-Word-DOCX"
Zip $tempFolder $name