Functions/Convert-CsvStringToExcelWorkbook.ps1
<#
.SYNOPSIS This function converts a CSV string into an Excel workbook. #> function Convert-CsvStringToExcelWorkbook { [CmdletBinding(PositionalBinding=$false)] [OutputType([OfficeOpenXml.ExcelPackage])] param ( # The CSV string containing the data which will be stored in the Excel workbook [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$csvString, # The path where the Excel workbook will be stored. [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$excelWorkbookFilePath, # The name of the worksheet that will hold the CSV data within the workbook. [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$excelWorksheetName ) # Test the workbook directory path $workbookDirectoryPath = Split-Path $excelWorkbookFilePath -Parent if (!(Test-Path -Path $workbookDirectoryPath -ErrorAction SilentlyContinue)) { Write-Error "The destination directory for Excel workbook '$($workbookDirectoryPath)' is not present." return } # Create the Excel workbook try { $csvObject = Convert-CsvStringToObject -CsvString $csvString $excelWorkbook = Export-Excel -Path $excelWorkbookFilePath -TargetData $csvObject -WorksheetName $excelWorksheetName -PassThru } catch { Write-Error "Error while converting CSV string to Excel workbook.`r`n$($_.Exception.Message)" return } if (!$excelWorkbook) { Write-Error "Failed to convert CSV string to Excel workbook." return } # Return the Excel workbook return $excelWorkbook } |