mirror of
https://github.com/dfinke/ImportExcel.git
synced 2025-12-10 05:13:49 +00:00
@@ -95,7 +95,7 @@ if (-not $VersionFilePath) {
|
||||
'[Info] Testing On:'
|
||||
Get-EnvironmentInfo
|
||||
'[Progress] Installing Module.'
|
||||
. .\Install.ps1
|
||||
. .\CI\Install.ps1
|
||||
'[Progress] Invoking Pester.'
|
||||
Invoke-Pester -OutputFile ('TestResultsPS{0}.xml' -f $PSVersionTable.PSVersion)
|
||||
}
|
||||
|
||||
@@ -81,8 +81,9 @@ function Invoke-MultiLike {
|
||||
}
|
||||
}
|
||||
|
||||
Push-Location "$PSScriptRoot\.."
|
||||
try {
|
||||
Write-Verbose -Message 'Module installation started'
|
||||
Write-Verbose -Message "Module installation started. Installing from $PWD"
|
||||
|
||||
if (!$ModulePath) {
|
||||
if ($Scope -eq 'CurrentUser') {
|
||||
@@ -99,6 +100,7 @@ try {
|
||||
}
|
||||
$ModulePath = ($env:PSModulePath -split $ModulePathSeparator)[$ModulePathIndex]
|
||||
}
|
||||
Write-Verbose -Message "Installing to $ModulePath"
|
||||
|
||||
# Get $ModuleName, $TargetPath, [$Links]
|
||||
if ($FromGitHub) {
|
||||
@@ -115,8 +117,8 @@ try {
|
||||
$ModuleVersion = (. ([Scriptblock]::Create((Invoke-WebRequest -Uri ($Links | Where-Object { $_.name -eq "$ModuleName.psd1" }).download_url)))).ModuleVersion
|
||||
}
|
||||
else {
|
||||
$ModuleName = [System.IO.Path]::GetFileNameWithoutExtension((Get-ChildItem -File -Filter *.psm1 -Name -Path $PSScriptRoot))
|
||||
$ModuleVersion = (. ([Scriptblock]::Create((Get-Content -Path (Join-Path $PSScriptRoot "$ModuleName.psd1") | Out-String)))).ModuleVersion
|
||||
$ModuleName = [System.IO.Path]::GetFileNameWithoutExtension((Get-ChildItem -File -Filter *.psm1 -Name -Path $PWD))
|
||||
$ModuleVersion = (. ([Scriptblock]::Create((Get-Content -Path (Join-Path $PWD "$ModuleName.psd1") | Out-String)))).ModuleVersion
|
||||
}
|
||||
$TargetPath = Join-Path -Path $ModulePath -ChildPath $ModuleName
|
||||
$TargetPath = Join-Path -Path $TargetPath -ChildPath $ModuleVersion
|
||||
@@ -160,7 +162,7 @@ try {
|
||||
}
|
||||
}
|
||||
else {
|
||||
Get-ChildItem -Path $PSScriptRoot -Exclude $ExcludeFiles | Where-Object { LikeAny $_.Name $IncludeFiles } | ForEach-Object {
|
||||
Get-ChildItem -Path $PWD -Exclude $ExcludeFiles | Where-Object { LikeAny $_.Name $IncludeFiles } | ForEach-Object {
|
||||
if ($_.Attributes -ne 'Directory') {
|
||||
Copy-Item -Path $_ -Destination $TargetPath
|
||||
Write-Verbose -Message ('Installed module file "{0}"' -f $_)
|
||||
@@ -185,4 +187,5 @@ finally {
|
||||
# [Net.ServicePointManager]::SecurityProtocol = $SecurityProtocol
|
||||
#}
|
||||
Write-Verbose -Message 'Module installation end'
|
||||
Pop-Location
|
||||
}
|
||||
255
CI/PS-CI.ps1
Normal file
255
CI/PS-CI.ps1
Normal file
@@ -0,0 +1,255 @@
|
||||
[cmdletbinding(DefaultParameterSetName='Scope')]
|
||||
Param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'ModulePath')]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[String]$ModulePath,
|
||||
|
||||
# Path to install the module to, PSModulePath "CurrentUser" or "AllUsers", if not provided "CurrentUser" used.
|
||||
[Parameter(ParameterSetName = 'Scope')]
|
||||
[ValidateSet('CurrentUser', 'AllUsers')]
|
||||
[string]
|
||||
$Scope = 'CurrentUser',
|
||||
|
||||
[Parameter(Mandatory=$true, ParameterSetName = 'PreCheckOnly')]
|
||||
[switch]$PreCheckOnly,
|
||||
[Parameter(ParameterSetName = 'ModulePath')]
|
||||
[Parameter(ParameterSetName = 'Scope')]
|
||||
[switch]$SkipPreChecks,
|
||||
[Parameter(ParameterSetName = 'ModulePath')]
|
||||
[Parameter(ParameterSetName = 'Scope')]
|
||||
[switch]$SkipPostChecks,
|
||||
[Parameter(ParameterSetName = 'ModulePath')]
|
||||
[Parameter(ParameterSetName = 'Scope')]
|
||||
[switch]$SkipPesterTests,
|
||||
[Parameter(ParameterSetName = 'ModulePath')]
|
||||
[Parameter(ParameterSetName = 'Scope')]
|
||||
[switch]$SkipHelp,
|
||||
[Parameter(ParameterSetName = 'ModulePath')]
|
||||
[Parameter(ParameterSetName = 'Scope')]
|
||||
[switch]$CleanModuleDir
|
||||
)
|
||||
Function Show-Warning {
|
||||
param(
|
||||
[Parameter(Position=0,ValueFromPipeline=$true)]
|
||||
$message
|
||||
)
|
||||
process {
|
||||
write-output "##vso[task.logissue type=warning]File $message"
|
||||
$message >> $script:warningfile
|
||||
}
|
||||
}
|
||||
|
||||
if ($PSScriptRoot) {
|
||||
$workingdir = Split-Path -Parent $PSScriptRoot
|
||||
Push-Location $workingdir
|
||||
}
|
||||
$psdpath = Get-Item "*.psd1"
|
||||
if (-not $psdpath -or $psdpath.count -gt 1) {
|
||||
if ($PSScriptRoot) { Pop-Location }
|
||||
throw "Did not find a unique PSD file "
|
||||
}
|
||||
else {
|
||||
try {$null = Test-ModuleManifest -Path $psdpath -ErrorAction stop}
|
||||
catch {throw $_ ; return}
|
||||
$ModuleName = $psdpath.Name -replace '\.psd1$' , ''
|
||||
$Settings = $(& ([scriptblock]::Create(($psdpath | Get-Content -Raw))))
|
||||
$approvedVerbs = Get-Verb | Select-Object -ExpandProperty verb
|
||||
$script:warningfile = Join-Path -Path $pwd -ChildPath "warnings.txt"
|
||||
}
|
||||
|
||||
#pre-build checks - manifest found, files in it found, public functions and aliases loaded in it. Public functions correct.
|
||||
if (-not $SkipPreChecks) {
|
||||
|
||||
#Check files in the manifest are present
|
||||
foreach ($file in $Settings.FileList) {
|
||||
if (-not (Test-Path $file)) {
|
||||
Show-Warning "File $file in the manifest file list is not present"
|
||||
}
|
||||
}
|
||||
|
||||
#Check files in public have Approved_verb-noun names and are 1 function using the file name as its name with
|
||||
# its name and any alias names in the manifest; function should have a param block and help should be in an MD file
|
||||
# We will want a regex which captures from "function verb-noun {" to its closing "}"
|
||||
# need to match each { to a } - $reg is based on https://stackoverflow.com/questions/7898310/using-regex-to-balance-match-parenthesis
|
||||
$reg = [Regex]::new(@"
|
||||
function\s*[-\w]+\s*{ # The function name and opening '{'
|
||||
(?:
|
||||
[^{}]+ # Match all non-braces
|
||||
|
|
||||
(?<open> { ) # Match '{', and capture into 'open'
|
||||
|
|
||||
(?<-open> } ) # Match '}', and delete the 'open' capture
|
||||
)*
|
||||
(?(open)(?!)) # Fails if 'open' stack isn't empty
|
||||
} # Functions closing '}'
|
||||
"@, 57) # 57 = compile,multi-line ignore case and white space.
|
||||
foreach ($file in (Get-Item .\Public\*.ps1)) {
|
||||
$name = $file.name -replace(".ps1","")
|
||||
if ($name -notmatch ("(\w+)-\w+")) {Show-Warning "$name in the public folder is not a verb-noun name"}
|
||||
elseif ($Matches[1] -notin $approvedVerbs) {Show-Warning "$name in the public folder does not start with an approved verb"}
|
||||
if(-not ($Settings.FunctionsToExport -ceq $name)) {
|
||||
Show-Warning ('File {0} in the public folder does not match an exported function in the manifest' -f $file.name)
|
||||
}
|
||||
else {
|
||||
$fileContent = Get-Content $file -Raw
|
||||
$m = $reg.Matches($fileContent)
|
||||
if ($m.Count -eq 0) {Show-Warning ('Could not find {0} function in {1}' -f $name, $file.name); continue}
|
||||
elseif ($m.Count -ge 2) {Show-Warning ('Multiple functions in {0}' -f $item.name) ; Continue}
|
||||
elseif ($m[0] -imatch "^\function\s" -and
|
||||
$m[0] -cnotmatch "^\w+\s+$name") {Show-Warning ('function name does not match file name for {0}' -f $file.name)}
|
||||
#$m[0] runs form the f of function to its final } -find the section up to param, check for aliases & comment-based help
|
||||
$m2 = [regex]::Match($m[0],"^.*?param",17) # 17 = multi-line, ignnore case
|
||||
if (-not $m2.Success) {Show-Warning "function $name has no param() block"}
|
||||
else {
|
||||
if ($m2.value -match "(?<!#\s*)\[\s*Alias\(\s*.([\w-]+).\s*\)\s*\]") {
|
||||
foreach ($a in ($Matches[1] -split '\s*,\s*')) {
|
||||
$a = $a -replace "'","" -replace '"',''
|
||||
if (-not ($Settings.AliasesToExport -eq $a)) {
|
||||
Show-Warning "Function $name has alias $a which is not in the manifest"
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($m2.value -match "\.syopsis|\.Description|\.Example") {
|
||||
Show-Warning "Function $name appears to have comment based help."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Warn about functions which are exported but not found in public
|
||||
$notFromPublic = $Settings.FunctionsToExport.Where({-not (Test-Path ".\public\$_.ps1")})
|
||||
If ($notFromPublic) {Show-Warning ('Exported function(s) {0} are not loaded from the Public folder' -f ($notFromPublic -join ', '))}
|
||||
}
|
||||
|
||||
if ($PreCheckOnly) {return}
|
||||
|
||||
#region build, determine module path if necessary, create target directory if necessary, copy files based on manifest, build help
|
||||
try {
|
||||
if ($ModulePath) {
|
||||
$ModulePath = $ModulePath -replace "\\$|/$",""
|
||||
}
|
||||
else {
|
||||
if ($IsLinux -or $IsMacOS) {$ModulePathSeparator = ':' }
|
||||
else {$ModulePathSeparator = ';' }
|
||||
if ($Scope -eq 'CurrentUser') {$dir = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile) }
|
||||
else {$dir = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::ProgramFiles) }
|
||||
$ModulePath = ($env:PSModulePath -split $ModulePathSeparator).where({$_ -like "$dir*"},"First",1)
|
||||
$ModulePath = Join-Path -Path $ModulePath -ChildPath $ModuleName
|
||||
$ModulePath = Join-Path -Path $ModulePath -ChildPath $Settings.ModuleVersion
|
||||
}
|
||||
# Clean-up / Create Directory
|
||||
if (-not (Test-Path -Path $ModulePath)) {
|
||||
$null = New-Item -Path $ModulePath -ItemType Directory -ErrorAction Stop
|
||||
'Created module folder: "{0}"' -f $ModulePath
|
||||
}
|
||||
elseif ($CleanModuleDir) {
|
||||
'{0} exists - cleaning before copy' -f $ModulePath
|
||||
Get-ChildItem -Path $ModulePath | Remove-Item -Force -Recurse
|
||||
}
|
||||
'Copying files to: "{0}"' -f $ModulePath
|
||||
$outputFile = $psdpath | Copy-Item -Destination $ModulePath -PassThru
|
||||
$outputFile.fullname
|
||||
foreach ($file in $Settings.FileList) {
|
||||
if ($file -like '.\*') {
|
||||
$dest = ($file -replace '\.\\',"$ModulePath\")
|
||||
if (-not (Test-Path -PathType Container (Split-Path -Parent $dest))) {
|
||||
$null = New-item -Type Directory -Path (Split-Path -Parent $dest)
|
||||
}
|
||||
}
|
||||
else {$dest = $ModulePath }
|
||||
Copy-Item -Path $file -Destination $dest -Force -Recurse
|
||||
}
|
||||
|
||||
if ((Test-Path -PathType Container "mdHelp") -and -not $SkipHelp) {
|
||||
if (-not (Get-Module -ListAvailable platyPS)) {
|
||||
'Installing Platyps to build help files'
|
||||
Install-Module -Name platyPS -Force -SkipPublisherCheck
|
||||
}
|
||||
$platypsInfo = Import-Module platyPS -PassThru -force
|
||||
Get-ChildItem .\mdHelp -Directory | ForEach-Object {
|
||||
'Building help for language ''{0}'', using {1} V{2}.' -f $_.Name,$platypsInfo.Name, $platypsInfo.Version
|
||||
$Null = New-ExternalHelp -Path $_.FullName -OutputPath (Join-Path $ModulePath $_.Name) -Force
|
||||
}
|
||||
}
|
||||
#Leave module path for things which follow.
|
||||
$env:PSNewBuildModule = $ModulePath
|
||||
}
|
||||
catch {
|
||||
if ($PSScriptRoot) { Pop-Location }
|
||||
throw ('Failed installing module "{0}". Error: "{1}" in Line {2}' -f $ModuleName, $_, $_.InvocationInfo.ScriptLineNumber)
|
||||
}
|
||||
finally {
|
||||
if (-not $outputFile -or -not (Test-Path $outputFile)) { throw "Failed to create module"}
|
||||
}
|
||||
#endregion
|
||||
|
||||
if ($env:Build_ArtifactStagingDirectory) {
|
||||
Copy-Item -Path (split-path -Parent $ModulePath) -Destination $env:Build_ArtifactStagingDirectory -Recurse
|
||||
}
|
||||
|
||||
#Check valid command names, help, run script analyzer over the files in the module directory
|
||||
if (-not $SkipPostChecks) {
|
||||
try {$outputFile | Import-Module -Force -ErrorAction stop }
|
||||
catch {
|
||||
if ($PSScriptRoot) { Pop-Location }
|
||||
throw "New module failed to load"
|
||||
}
|
||||
$commands = Get-Command -Module $ModuleName -CommandType function,Cmdlet
|
||||
$commands.where({$_.name -notmatch "(\w+)-\w+" -or $Matches[1] -notin $approvedVerbs}) | ForEach-Object {
|
||||
Show-Warning ('{0} does not meet the ApprovedVerb-Noun naming rules' -f $_.name)
|
||||
}
|
||||
$helpless = $commands | Get-Help | Where-Object {$_.Synopsis -match "^\s+$($_.name)\s+\["} | Select-Object -ExpandProperty name
|
||||
foreach ($command in $helpless ) {
|
||||
Show-Warning ('On-line help is missing for {0}.' -f $command)
|
||||
}
|
||||
if (-not (Get-Module -Name PSScriptAnalyzer -ListAvailable)) {
|
||||
Install-Module -Name PSScriptAnalyzer -Force
|
||||
}
|
||||
$PSSAInfo = Import-module -Name PSScriptAnalyzer -PassThru -force
|
||||
"Running {1} V{2} against '{0}' " -f $ModulePath , $PSSAInfo.name, $PSSAInfo.Version
|
||||
$AnalyzerResults = Invoke-ScriptAnalyzer -Path $ModulePath -Recurse -ErrorAction SilentlyContinue
|
||||
if ($AnalyzerResults) {
|
||||
if (-not (Get-Module -Name ImportExcel -ListAvailable)) {
|
||||
#ironically we use this to build import-excel Shouldn't need this there!
|
||||
'Installing ImportExcel.'
|
||||
Install-Module -Name ImportExcel -Force
|
||||
}
|
||||
$chartDef = New-ExcelChartDefinition -ChartType 'BarClustered' -Column 2 -Title "Script analysis" -LegendBold
|
||||
$ExcelParams = @{
|
||||
Path = (Join-Path $pwd 'ScriptAnalyzer.xlsx')
|
||||
WorksheetName = 'FullResults'
|
||||
TableStyle = 'Medium6'
|
||||
AutoSize = $true
|
||||
Activate = $true
|
||||
PivotTableDefinition = @{BreakDown = @{
|
||||
PivotData = @{RuleName = 'Count' }
|
||||
PivotRows = 'Severity', 'RuleName'
|
||||
PivotTotals = 'Rows'
|
||||
PivotChartDefinition = $chartDef }}
|
||||
}
|
||||
Remove-Item -Path $ExcelParams['Path'] -ErrorAction SilentlyContinue
|
||||
$AnalyzerResults | Export-Excel @ExcelParams
|
||||
if (Test-Path $ExcelParams['Path']) {
|
||||
"Try to uploadfile {0}" -f $ExcelParams['Path']
|
||||
"##vso[task.uploadfile]{0}" -f $ExcelParams['Path']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Test-Path $script:warningfile) {
|
||||
"Try to uploadfile {0}" -f $script:warningfile
|
||||
"##vso[task.uploadfile]{0}" -f $script:warningfile
|
||||
}
|
||||
|
||||
#if there are test files, run pester (unless told not to)
|
||||
if (-not $SkipPesterTests -and (Get-ChildItem -Recurse *.tests.ps1)) {
|
||||
Import-Module -Force $outputFile
|
||||
if (-not (Get-Module -ListAvailable pester | Where-Object -Property version -ge ([version]::new(4,4,1)))) {
|
||||
Install-Module Pester -Force -SkipPublisherCheck
|
||||
}
|
||||
Import-Module Pester
|
||||
$PesterOutputPath = Join-Path $pwd -ChildPath ('TestResultsPS{0}.xml' -f $PSVersionTable.PSVersion)
|
||||
if ($PSScriptRoot) { Pop-Location }
|
||||
Invoke-Pester -OutputFile $PesterOutputPath
|
||||
}
|
||||
elseif ($PSScriptRoot) { Pop-Location }
|
||||
@@ -10,11 +10,10 @@ param(
|
||||
[ValidateSet('CurrentUser', 'AllUsers')]
|
||||
[string]
|
||||
$Scope = 'CurrentUser',
|
||||
[switch]$Passthru,
|
||||
[switch]$Tests
|
||||
[switch]$Passthru
|
||||
)
|
||||
|
||||
if ($PSScriptRoot) { Push-Location $PSScriptRoot }
|
||||
if ($PSScriptRoot) { Push-Location "$PSScriptRoot\.." }
|
||||
|
||||
$psdpath = Get-Item "*.psd1"
|
||||
if (-not $psdpath -or $psdpath.count -gt 1) {
|
||||
@@ -76,5 +75,6 @@ catch {
|
||||
throw ('Failed installing module "{0}". Error: "{1}" in Line {2}' -f $ModuleName, $_, $_.InvocationInfo.ScriptLineNumber)
|
||||
}
|
||||
finally {
|
||||
if ($PSScriptRoot) { Pop-Location }
|
||||
Write-Verbose -Message 'Module installation end'
|
||||
}
|
||||
75
CI/pipeline.yml
Normal file
75
CI/pipeline.yml
Normal file
@@ -0,0 +1,75 @@
|
||||
# https://aka.ms/yaml
|
||||
|
||||
trigger:
|
||||
branches:
|
||||
include:
|
||||
- '*'
|
||||
# - master
|
||||
# - releases/*
|
||||
paths:
|
||||
exclude:
|
||||
- README.md
|
||||
- CHANGELOG.md
|
||||
|
||||
jobs:
|
||||
- job: 'Windows_PowerShell_all_options'
|
||||
pool:
|
||||
vmImage: 'windows-latest'
|
||||
steps:
|
||||
- powershell: 'Install-Module -Name Pester -Force -SkipPublisherCheck'
|
||||
displayName: 'Update Pester'
|
||||
- powershell: './CI/PS-CI.ps1 '
|
||||
displayName: 'Check Build Check Pack Test'
|
||||
- task: PublishTestResults@2
|
||||
inputs:
|
||||
testResultsFormat: 'NUnit'
|
||||
testResultsFiles: '**/TestResults*.xml'
|
||||
failTaskOnFailedTests: true
|
||||
- task: PublishPipelineArtifact@1
|
||||
inputs:
|
||||
targetPath: '$(Build.ArtifactStagingDirectory)/ImportExcel'
|
||||
artifact: 'ImportExcel'
|
||||
|
||||
- job: 'PowerShell_Core_on_Windows_Build_and_Pester_only'
|
||||
pool:
|
||||
vmImage: 'windows-latest'
|
||||
steps:
|
||||
- pwsh: 'Install-Module -Name Pester -Force'
|
||||
displayName: 'Update Pester'
|
||||
- pwsh: '.\CI\PS-CI.ps1 -SkipPreChecks -SkipHelp -SkipPostChecks'
|
||||
displayName: 'Install and Test'
|
||||
- task: PublishTestResults@2
|
||||
inputs:
|
||||
testResultsFormat: 'NUnit'
|
||||
testResultsFiles: '**/TestResults*.xml'
|
||||
failTaskOnFailedTests: true
|
||||
|
||||
- job: 'Ubuntu_Build_and_Pester_Only'
|
||||
pool:
|
||||
vmImage: 'ubuntu-latest'
|
||||
steps:
|
||||
- powershell: 'Install-Module -Name Pester -Force'
|
||||
displayName: 'Update Pester'
|
||||
- powershell: './CI/PS-CI.ps1 -SkipPreChecks -SkipHelp -SkipPostChecks '
|
||||
displayName: 'Install and Test'
|
||||
- task: PublishTestResults@2
|
||||
inputs:
|
||||
testResultsFormat: 'NUnit'
|
||||
testResultsFiles: '**/TestResults*.xml'
|
||||
failTaskOnFailedTests: true
|
||||
|
||||
- job: 'macOS_Build_and_Pester_Only'
|
||||
pool:
|
||||
vmImage: 'macOS-latest'
|
||||
steps:
|
||||
- script: brew install mono-libgdiplus
|
||||
displayName: 'Install mono-libgdiplus'
|
||||
- powershell: 'Install-Module -Name Pester -Force'
|
||||
displayName: 'Update Pester'
|
||||
- powershell: './CI/PS-CI.ps1 -SkipPreChecks -SkipHelp -SkipPostChecks'
|
||||
displayName: 'Install and Test'
|
||||
- task: PublishTestResults@2
|
||||
inputs:
|
||||
testResultsFormat: 'NUnit'
|
||||
testResultsFiles: '**/TestResults*.xml'
|
||||
failTaskOnFailedTests: true
|
||||
@@ -22,7 +22,7 @@ $ws = $excel.Music
|
||||
Set-ExcelRow -Worksheet $ws -Row 1 -Value {($worksheet.cells[$row,$column].value -replace '^SYSTEM\.','') -replace '^MEDIA\.|^AUDIO\.|^MUSIC\.','' }
|
||||
Set-ExcelColumn -Worksheet $ws -Column 5 -NumberFormat 'mm:ss.0' -StartRow 2 -Value {$worksheet.cells[$row,$column].value / 864000000000 }
|
||||
Write-Verbose -Message ("Cells Reset: " + $stopwatch.Elapsed.TotalSeconds)
|
||||
Set-Column -Worksheet $ws -Column 6 -NumberFormat '#.#,,"MB"'
|
||||
Set-ExcelColumn -Worksheet $ws -Column 6 -NumberFormat '#.#,,"MB"'
|
||||
Set-ExcelColumn -Worksheet $ws -Column 7 -NumberFormat '0.0,"KHz"'
|
||||
$ws.Cells[$ws.Dimension].AutoFitColumns()
|
||||
|
||||
|
||||
@@ -83,6 +83,6 @@ Set-ExcelColumn -ExcelPackage $Excel -WorkSheetname "Winners" -column 7 -Head
|
||||
6..7 | ForEach-Object {
|
||||
Set-ExcelRange -Address $Excel.Workbook.Worksheets["Winners"].column($_) -NumberFormat "0.0%" -AutoFit }
|
||||
#Define a chart to show the relationship of lest on an XY Grid, create the ranges required in the, add the chart and show the file in Excel in excel after saving.
|
||||
$chart = New-ExcelChart -NoLegend -ChartType XYScatter -XRange WinsToFast -YRange WinsToPoles -ShowCategory -Column 7 -Width 2000 -Height 700
|
||||
$chart = New-ExcelChartDefinition -NoLegend -ChartType XYScatter -XRange WinsToFast -YRange WinsToPoles -ShowCategory -Column 7 -Width 2000 -Height 700
|
||||
Export-Excel -ExcelPackage $Excel -WorkSheetname "Winners" -AutoNameRange -ExcelChartDefinition $chart -Show
|
||||
|
||||
|
||||
@@ -15,10 +15,10 @@ $Excel = Send-SQLDataToExcel -SQL $sql -Session $session -path .\demo3.xlsx -
|
||||
|
||||
$ws = $Excel.Workbook.Worksheets["Winners"]
|
||||
|
||||
Set-Row -Worksheet $ws -Heading "Average" -Value {"=Average($columnName`2:$columnName$endrow)"} -NumberFormat "0.0" -Bold
|
||||
Set-Column -Worksheet $ws -Heading "WinsToPoles" -Value {"=D$row/C$row"} -Column 6 -AutoSize -AutoNameRange
|
||||
Set-Column -Worksheet $ws -Heading "WinsToFast" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange
|
||||
Set-ExcelRow -Worksheet $ws -Heading "Average" -Value {"=Average($columnName`2:$columnName$endrow)"} -NumberFormat "0.0" -Bold
|
||||
Set-ExcelColumn -Worksheet $ws -Heading "WinsToPoles" -Value {"=D$row/C$row"} -Column 6 -AutoSize -AutoNameRange
|
||||
Set-ExcelColumn -Worksheet $ws -Heading "WinsToFast" -Value {"=E$row/C$row"} -Column 7 -AutoSize -AutoNameRange
|
||||
|
||||
Set-ExcelRange -Worksheet $ws -Range "F2:G50" -NumberFormat "0.0%"
|
||||
$chart = New-ExcelChart -NoLegend -ChartType XYScatter -XRange WinsToFast -YRange WinsToPoles -Column 7 -Width 2000 -Height 700 -Title "Poles vs fastlaps"
|
||||
$chart = New-ExcelChartDefinition -NoLegend -ChartType XYScatter -XRange WinsToFast -YRange WinsToPoles -Column 7 -Width 2000 -Height 700 -Title "Poles vs fastlaps"
|
||||
Export-Excel -ExcelPackage $Excel -WorkSheetname "Winners" -ExcelChartDefinition $chart -Show
|
||||
@@ -26,38 +26,7 @@ PowerShell module to import/export Excel spreadsheets, without Excel.
|
||||
Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5uoqS92stXioZw-u-ze_NtvSo0k0K0kq
|
||||
'@
|
||||
|
||||
# Minimum version of the Windows PowerShell engine required by this module
|
||||
# PowerShellVersion = ''
|
||||
|
||||
# Name of the Windows PowerShell host required by this module
|
||||
# PowerShellHostName = ''
|
||||
|
||||
# Minimum version of the Windows PowerShell host required by this module
|
||||
# PowerShellHostVersion = ''
|
||||
|
||||
# Minimum version of Microsoft .NET Framework required by this module
|
||||
# DotNetFrameworkVersion = ''
|
||||
|
||||
# Minimum version of the common language runtime (CLR) required by this module
|
||||
# CLRVersion = ''
|
||||
|
||||
# Processor architecture (None, X86, Amd64) required by this module
|
||||
# ProcessorArchitecture = ''
|
||||
|
||||
# Modules that must be imported into the global environment prior to importing this module
|
||||
# RequiredModules = @()
|
||||
|
||||
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
|
||||
# ScriptsToProcess = @()
|
||||
|
||||
# Type files (.ps1xml) to be loaded when importing this module
|
||||
# TypesToProcess = @()
|
||||
|
||||
# Format files (.ps1xml) to be loaded when importing this module
|
||||
# FormatsToProcess = @()
|
||||
|
||||
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
|
||||
# NestedModules = @()
|
||||
|
||||
# Functions to export from this module
|
||||
FunctionsToExport = @(
|
||||
@@ -125,15 +94,10 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5
|
||||
'Update-FirstObjectProperties'
|
||||
)
|
||||
|
||||
# Cmdlets to export from this module
|
||||
#CmdletsToExport = '*'
|
||||
|
||||
# Variables to export from this module
|
||||
#VariablesToExport = '*'
|
||||
|
||||
# Aliases to export from this module
|
||||
AliasesToExport = @(
|
||||
'Convert-XlRangeToImage'
|
||||
'Convert-XlRangeToImage',
|
||||
'Export-ExcelSheet',
|
||||
'New-ExcelChart',
|
||||
'Set-Column',
|
||||
'Set-Format',
|
||||
@@ -141,10 +105,9 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5
|
||||
'Use-ExcelData'
|
||||
)
|
||||
|
||||
# List of all modules packaged with this module
|
||||
# ModuleList = @()
|
||||
# Cmdlets to export from this module
|
||||
CmdletsToExport = @()
|
||||
|
||||
# List of all files packaged with this module
|
||||
FileList = @(
|
||||
'.\EPPlus.dll',
|
||||
'.\Export-charts.ps1',
|
||||
@@ -153,13 +116,16 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5
|
||||
'.\ImportExcel.psm1',
|
||||
'.\LICENSE.txt',
|
||||
'.\README.md',
|
||||
'.\Plot.ps1',
|
||||
'.\Private',
|
||||
'.\Public',
|
||||
'.\en\ImportExcel-help.xml',
|
||||
'.\en\Strings.psd1',
|
||||
'.\Charting\Charting.ps1',
|
||||
'.\InferData\InferData.ps1',
|
||||
'.\Pivot\Pivot.ps1',
|
||||
'.\spikes\ConvertFrom-ExcelColumnName.ps1',
|
||||
'.\Examples', '.\images', '.\Testimonials' , '.\Public'
|
||||
'.\Examples', '.\images', '.\Testimonials'
|
||||
|
||||
)
|
||||
|
||||
@@ -196,6 +162,46 @@ Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5
|
||||
}
|
||||
}
|
||||
|
||||
# Minimum version of the Windows PowerShell engine required by this module
|
||||
# PowerShellVersion = ''
|
||||
|
||||
# Name of the Windows PowerShell host required by this module
|
||||
# PowerShellHostName = ''
|
||||
|
||||
# Minimum version of the Windows PowerShell host required by this module
|
||||
# PowerShellHostVersion = ''
|
||||
|
||||
# Minimum version of Microsoft .NET Framework required by this module
|
||||
# DotNetFrameworkVersion = ''
|
||||
|
||||
# Minimum version of the common language runtime (CLR) required by this module
|
||||
# CLRVersion = ''
|
||||
|
||||
# Processor architecture (None, X86, Amd64) required by this module
|
||||
# ProcessorArchitecture = ''
|
||||
|
||||
# Modules that must be imported into the global environment prior to importing this module
|
||||
# RequiredModules = @()
|
||||
|
||||
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
|
||||
# ScriptsToProcess = @()
|
||||
|
||||
# Type files (.ps1xml) to be loaded when importing this module
|
||||
# TypesToProcess = @()
|
||||
|
||||
# Format files (.ps1xml) to be loaded when importing this module
|
||||
# FormatsToProcess = @()
|
||||
|
||||
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
|
||||
# NestedModules = @()
|
||||
|
||||
# List of all modules packaged with this module
|
||||
# ModuleList = @()
|
||||
|
||||
# List of all files packaged with this module
|
||||
# Variables to export from this module
|
||||
#VariablesToExport = '*'
|
||||
|
||||
# HelpInfo URI of this module
|
||||
# HelpInfoURI = ''
|
||||
|
||||
|
||||
@@ -5,14 +5,12 @@ if (-not $Strings) {
|
||||
Import-LocalizedData -UICulture "en" -BindingVariable Strings -FileName Strings -ErrorAction Ignore
|
||||
}
|
||||
try { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") }
|
||||
catch { Write-Warning -Message $Strings.SystemDrawingAvaialable }
|
||||
catch { Write-Warning -Message $Strings.SystemDrawingAvailable }
|
||||
|
||||
foreach ($directory in @('Public', 'Charting', 'InferData', 'Pivot')) {
|
||||
Get-ChildItem -Path "$PSScriptRoot\$directory\*.ps1" | ForEach-Object { . $_.FullName }
|
||||
foreach ($directory in @('Private', 'Public','Charting','InferData','Pivot')) {
|
||||
Get-ChildItem -Path "$PSScriptRoot\$directory\*.ps1" | ForEach-Object {. $_.FullName}
|
||||
}
|
||||
|
||||
. $PSScriptRoot\ArgumentCompletion.ps1
|
||||
|
||||
if ($PSVersionTable.PSVersion.Major -ge 5) {
|
||||
. $PSScriptRoot\Plot.ps1
|
||||
|
||||
|
||||
@@ -1,48 +1,42 @@
|
||||
function ConvertFrom-ExcelSheet {
|
||||
[CmdletBinding()]
|
||||
param
|
||||
(
|
||||
[Alias("FullName")]
|
||||
[Alias("Export-ExcelSheet")]
|
||||
param (
|
||||
[Parameter(Mandatory = $true)]
|
||||
[String]
|
||||
$Path,
|
||||
[String]
|
||||
$OutputPath = '.\',
|
||||
[String]
|
||||
$SheetName = "*",
|
||||
[ValidateSet('ASCII', 'BigEndianUniCode', 'Default', 'OEM', 'UniCode', 'UTF32', 'UTF7', 'UTF8')]
|
||||
[string]
|
||||
$Encoding = 'UTF8',
|
||||
[ValidateSet('.txt', '.log', '.csv')]
|
||||
[string]
|
||||
$Extension = '.csv',
|
||||
[String]$Path,
|
||||
[String]$OutputPath = '.\',
|
||||
[String]$SheetName = "*",
|
||||
[ValidateSet('ASCII', 'BigEndianUniCode','Default','OEM','UniCode','UTF32','UTF7','UTF8')]
|
||||
[string]$Encoding = 'UTF8',
|
||||
[ValidateSet('.txt', '.log','.csv')]
|
||||
[string]$Extension = '.csv',
|
||||
[ValidateSet(';', ',')]
|
||||
[string]
|
||||
$Delimiter = ';'
|
||||
[string]$Delimiter ,
|
||||
$Property = "*",
|
||||
$ExcludeProperty = @(),
|
||||
[switch]$Append,
|
||||
[string[]]$AsText = @()
|
||||
)
|
||||
|
||||
$Path = (Resolve-Path $Path).Path
|
||||
$Stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path, "Open", "Read", "ReadWrite"
|
||||
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Stream
|
||||
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path
|
||||
$workbook = $xl.Workbook
|
||||
|
||||
$targetSheets = $workbook.Worksheets | Where-Object { $_.Name -like $SheetName }
|
||||
$targetSheets = $workbook.Worksheets | Where-Object {$_.Name -Like $SheetName}
|
||||
|
||||
$params = @{ } + $PSBoundParameters
|
||||
$params.Remove("OutputPath")
|
||||
$params.Remove("SheetName")
|
||||
$params.Remove('Extension')
|
||||
$params.NoTypeInformation = $true
|
||||
$csvParams = @{NoTypeInformation = $true} + $PSBoundParameters
|
||||
foreach ($p in 'OutputPath', 'SheetName', 'Extension', 'Property','ExcludeProperty', 'AsText') {
|
||||
$csvParams.Remove($p)
|
||||
}
|
||||
|
||||
Foreach ($sheet in $targetSheets) {
|
||||
Write-Verbose "Exporting sheet: $($sheet.Name)"
|
||||
|
||||
$params.Path = "$OutputPath\$($Sheet.Name)$Extension"
|
||||
$csvParams.Path = "$OutputPath\$($Sheet.Name)$Extension"
|
||||
|
||||
Import-Excel $Path -Sheet $($sheet.Name) | Export-Csv @params
|
||||
}
|
||||
Import-Excel -ExcelPackage $xl -Sheet $($sheet.Name) -AsText:$AsText |
|
||||
Select-Object -Property $Property | Export-Csv @csvparams
|
||||
}
|
||||
|
||||
$Stream.Close()
|
||||
$Stream.Dispose()
|
||||
$xl.Dispose()
|
||||
}
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
---
|
||||
external help file: ImportExcel-help.xml
|
||||
Module Name: ImportExcel
|
||||
online version: https://github.com/dfinke/ImportExcel
|
||||
schema: 2.0.0
|
||||
---
|
||||
|
||||
# Export-ExcelSheet
|
||||
|
||||
## SYNOPSIS
|
||||
{{ Fill in the Synopsis }}
|
||||
|
||||
## SYNTAX
|
||||
|
||||
```
|
||||
Export-ExcelSheet [-Path] <String> [[-OutputPath] <String>] [[-SheetName] <String>] [[-Encoding] <String>] [[-Extension] <String>] [[-Delimiter] <String>] [<CommonParameters>]
|
||||
```
|
||||
|
||||
## DESCRIPTION
|
||||
{{ Fill in the Description }}
|
||||
|
||||
## EXAMPLES
|
||||
|
||||
### Example 1
|
||||
```powershell
|
||||
PS C:\> {{ Add example code here }}
|
||||
```
|
||||
|
||||
{{ Add example description here }}
|
||||
|
||||
## PARAMETERS
|
||||
|
||||
### -Delimiter
|
||||
{{ Fill Delimiter Description }}
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
Accepted values: ;, ,
|
||||
|
||||
Required: False
|
||||
Position: 5
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Encoding
|
||||
{{ Fill Encoding Description }}
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
Accepted values: ASCII, BigEndianUniCode, Default, OEM, UniCode, UTF32, UTF7, UTF8
|
||||
|
||||
Required: False
|
||||
Position: 3
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Extension
|
||||
{{ Fill Extension Description }}
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
Accepted values: .txt, .log, .csv
|
||||
|
||||
Required: False
|
||||
Position: 4
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -OutputPath
|
||||
{{ Fill OutputPath Description }}
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 1
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Path
|
||||
{{ Fill Path Description }}
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: True
|
||||
Position: 0
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -SheetName
|
||||
{{ Fill SheetName Description }}
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 2
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### CommonParameters
|
||||
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
|
||||
|
||||
## INPUTS
|
||||
|
||||
### None
|
||||
|
||||
## OUTPUTS
|
||||
|
||||
### System.Object
|
||||
## NOTES
|
||||
|
||||
## RELATED LINKS
|
||||
@@ -1,39 +0,0 @@
|
||||
function Export-ExcelSheet {
|
||||
[CmdletBinding()]
|
||||
param
|
||||
(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[String]$Path,
|
||||
[String]$OutputPath = '.\',
|
||||
[String]$SheetName,
|
||||
[ValidateSet('ASCII', 'BigEndianUniCode','Default','OEM','UniCode','UTF32','UTF7','UTF8')]
|
||||
[string]$Encoding = 'UTF8',
|
||||
[ValidateSet('.txt', '.log','.csv')]
|
||||
[string]$Extension = '.csv',
|
||||
[ValidateSet(';', ',')]
|
||||
[string]$Delimiter = ';'
|
||||
)
|
||||
|
||||
$Path = (Resolve-Path $Path).Path
|
||||
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path
|
||||
$workbook = $xl.Workbook
|
||||
|
||||
$targetSheets = $workbook.Worksheets | Where-Object {$_.Name -Match $SheetName}
|
||||
|
||||
$params = @{} + $PSBoundParameters
|
||||
$params.Remove("OutputPath")
|
||||
$params.Remove("SheetName")
|
||||
$params.Remove('Extension')
|
||||
$params.NoTypeInformation = $true
|
||||
|
||||
Foreach ($sheet in $targetSheets)
|
||||
{
|
||||
Write-Verbose "Exporting sheet: $($sheet.Name)"
|
||||
|
||||
$params.Path = "$OutputPath\$($Sheet.Name)$Extension"
|
||||
|
||||
Import-Excel $Path -Sheet $($sheet.Name) | Export-Csv @params
|
||||
}
|
||||
|
||||
$xl.Dispose()
|
||||
}
|
||||
@@ -89,7 +89,7 @@ function Merge-MultipleSheets {
|
||||
if ($filesToProcess.Count -ge 2) {
|
||||
$refPrefix = (Split-Path -Path $filestoProcess[0] -Leaf) -replace "\.xlsx$"," "
|
||||
}
|
||||
else {$refPrefix = $WorksheetName[0] }
|
||||
else {$refPrefix = $WorksheetName[0] + " "}
|
||||
Write-Progress -Activity "Merging sheets" -CurrentOperation "applying formatting to sheet '$OutputSheetName' in $OutputFile"
|
||||
#Find the column headings which are in the form "diffFile is"; which will hold 'Same', 'Added' or 'Changed'
|
||||
foreach ($cell in $sheet.Cells[($sheet.Dimension.Address -replace "\d+$","1")].Where({$_.value -match "\sIS$"}) ) {
|
||||
|
||||
@@ -3,27 +3,28 @@ function New-ConditionalText {
|
||||
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')]
|
||||
param(
|
||||
#[Parameter(Mandatory=$true)]
|
||||
[Alias("ConditionValue")]
|
||||
[Alias('ConditionValue')]
|
||||
$Text,
|
||||
[Alias("ForeGroundColor")]
|
||||
[Alias('ForeGroundColor')]
|
||||
$ConditionalTextColor=[System.Drawing.Color]::DarkRed,
|
||||
$BackgroundColor=[System.Drawing.Color]::LightPink,
|
||||
[String]$Range,
|
||||
[OfficeOpenXml.Style.ExcelFillStyle]$PatternType=[OfficeOpenXml.Style.ExcelFillStyle]::Solid,
|
||||
[ValidateSet(
|
||||
"LessThan", "LessThanOrEqual", "GreaterThan", "GreaterThanOrEqual",
|
||||
"Equal", "NotEqual",
|
||||
"Top", "TopPercent", "Bottom", "BottomPercent",
|
||||
"ContainsText", "NotContainsText", "BeginsWith", "EndsWith",
|
||||
"ContainsBlanks", "NotContainsBlanks", "ContainsErrors", "NotContainsErrors",
|
||||
"DuplicateValues", "UniqueValues",
|
||||
"Tomorrow", "Today", "Yesterday", "Last7Days",
|
||||
"NextWeek", "ThisWeek", "LastWeek",
|
||||
"NextMonth", "ThisMonth", "LastMonth",
|
||||
"AboveAverage", "AboveOrEqualAverage", "BelowAverage", "BelowOrEqualAverage"
|
||||
'LessThan', 'LessThanOrEqual', 'GreaterThan', 'GreaterThanOrEqual',
|
||||
'Equal', 'NotEqual',
|
||||
'Top', 'TopPercent', 'Bottom', 'BottomPercent',
|
||||
'ContainsText', 'NotContainsText', 'BeginsWith', 'EndsWith',
|
||||
'ContainsBlanks', 'NotContainsBlanks', 'ContainsErrors', 'NotContainsErrors',
|
||||
'DuplicateValues', 'UniqueValues',
|
||||
'Tomorrow', 'Today', 'Yesterday', 'Last7Days',
|
||||
'NextWeek', 'ThisWeek', 'LastWeek',
|
||||
'NextMonth', 'ThisMonth', 'LastMonth',
|
||||
'AboveAverage', 'AboveOrEqualAverage', 'BelowAverage', 'BelowOrEqualAverage',
|
||||
'Expression'
|
||||
)]
|
||||
[Alias("RuleType")]
|
||||
$ConditionalType="ContainsText"
|
||||
[Alias('RuleType')]
|
||||
$ConditionalType='ContainsText'
|
||||
)
|
||||
|
||||
$obj = [PSCustomObject]@{
|
||||
|
||||
@@ -59,7 +59,16 @@ Describe "Compare Worksheet" {
|
||||
|
||||
Context "Setting the background to highlight different rows" {
|
||||
BeforeAll {
|
||||
$null = Compare-Worksheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen)
|
||||
if ($PSVersionTable.PSVersion.Major -ne 5) {
|
||||
$null = Compare-Worksheet "TestDrive:\server1.xlsx" "TestDrive:\server2.xlsx" -BackgroundColor ([System.Drawing.Color]::LightGreen)
|
||||
}
|
||||
else {
|
||||
$cmdline = 'Import-Module {0}; $null = Compare-WorkSheet "{1}" "{2}" -BackgroundColor ([System.Drawing.Color]::LightGreen) -GridView; Start-Sleep -sec 5; exit'
|
||||
$cmdline = $cmdline -f (Resolve-Path "$PSScriptRoot\..\importExcel.psd1" ) ,
|
||||
(Join-Path (Get-PSDrive TestDrive).root "server1.xlsx"),
|
||||
(Join-Path (Get-PSDrive TestDrive).root "server2.xlsx")
|
||||
powershell.exe -Command $cmdline
|
||||
}
|
||||
$xl1 = Open-ExcelPackage -Path "TestDrive:\server1.xlsx"
|
||||
$xl2 = Open-ExcelPackage -Path "TestDrive:\server2.xlsx"
|
||||
$s1Sheet = $xl1.Workbook.Worksheets[1]
|
||||
|
||||
36
__tests__/ConvertFrom-ExcelSheet.Tests.ps1
Normal file
36
__tests__/ConvertFrom-ExcelSheet.Tests.ps1
Normal file
@@ -0,0 +1,36 @@
|
||||
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
|
||||
$scriptPath = Split-Path -Path $MyInvocation.MyCommand.path -Parent
|
||||
$dataPath = Join-Path -Path $scriptPath -ChildPath "First10Races.xlsx"
|
||||
$Outpath = "TestDrive:\"
|
||||
|
||||
Describe 'ConvertFrom-ExcelSheet / Export-ExcelSheet' {
|
||||
BeforeAll {
|
||||
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath
|
||||
$firstText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
|
||||
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText GridPosition,date
|
||||
$SecondText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
|
||||
ConvertFrom-ExcelSheet -Path $dataPath -OutputPath $Outpath -AsText "GridPosition" -Property driver,
|
||||
@{n="date"; e={[datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#")}} , FinishPosition, GridPosition
|
||||
$ThirdText = Get-Content (Join-path -Path $Outpath -ChildPath "First10Races.csv")
|
||||
}
|
||||
Context "Exporting to CSV" {
|
||||
it "Exported the expected columns to a CSV file " {
|
||||
$firstText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"'
|
||||
$SecondText[0] | should be '"Race","Date","FinishPosition","Driver","GridPosition","Team","Points"'
|
||||
$ThirdText[0] | should be '"Driver","date","FinishPosition","GridPosition"'
|
||||
}
|
||||
it "Applied ASText and Properties correctly " {
|
||||
$firstText[1] | should match '^"\w+","\d{5}","\d{1,2}","\w+ \w+","[1-9]\d?","\w+","\d{1,2}"$'
|
||||
$date = $firstText[1] -replace '^.*(\d{5}).*$', '$1'
|
||||
$date = [datetime]::FromOADate($date).toString("D")
|
||||
$secondText[1] | should belike "*$date*"
|
||||
$secondText[1] | should match '"0\d","\w+","\d{1,2}"$'
|
||||
$ThirdText[1] | should match '^"\w+ \w+","#\d\d/\d\d/\d{4}#","\d","0\d"$'
|
||||
}
|
||||
}
|
||||
Context "Export aliased to ConvertFrom" {
|
||||
it "Applied ASText and Properties correctly " {
|
||||
(Get-Alias Export-ExcelSheet).source | should be "ImportExcel"
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
__tests__/First10Races.xlsx
Normal file
BIN
__tests__/First10Races.xlsx
Normal file
Binary file not shown.
@@ -17,11 +17,11 @@ $map = @{
|
||||
16384 = 'XFD'
|
||||
}
|
||||
|
||||
(Get-ExcelColumnName 26).columnName | Should be 'Z'
|
||||
(Get-ExcelColumnName 27).columnName | Should be 'AA'
|
||||
(Get-ExcelColumnName 26).columnName | Should be 'Z'
|
||||
(Get-ExcelColumnName 27).columnName | Should be 'AA'
|
||||
(Get-ExcelColumnName 28).columnNamee | Should be 'AB'
|
||||
(Get-ExcelColumnName 30).columnName | Should be 'AD'
|
||||
(Get-ExcelColumnName 48).columnName | Should be 'AV'
|
||||
(Get-ExcelColumnName 30).columnName | Should be 'AD'
|
||||
(Get-ExcelColumnName 48).columnName | Should be 'AV'
|
||||
|
||||
1..16 | ForEach-Object {
|
||||
$number = $_ * 1024
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','',Justification='False Positives')]
|
||||
Param()
|
||||
if (-not (Get-command Import-Excel -ErrorAction SilentlyContinue)) {
|
||||
Import-Module $PSScriptRoot\..\..\ImportExcel.psd1
|
||||
}
|
||||
|
||||
Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 -Force
|
||||
|
||||
Describe "Tests" {
|
||||
BeforeAll {
|
||||
$data = $null
|
||||
@@ -10,17 +10,20 @@ Describe "Tests" {
|
||||
$data = Import-Excel $PSScriptRoot\Simple.xlsx
|
||||
}
|
||||
}
|
||||
|
||||
It "Should have two items".PadRight(90) {
|
||||
It "Should have a valid manifest".PadRight(90){
|
||||
{try {Test-ModuleManifest -Path $PSScriptRoot\..\..\ImportExcel.psd1 -ErrorAction stop}
|
||||
catch {throw} } | should not throw
|
||||
}
|
||||
It "Should have two items in the imported simple data".PadRight(90) {
|
||||
$data.count | Should be 2
|
||||
}
|
||||
|
||||
It "Should have items a and b".PadRight(90) {
|
||||
It "Should have items a and b in the imported simple data".PadRight(90) {
|
||||
$data[0].p1 | Should be "a"
|
||||
$data[1].p1 | Should be "b"
|
||||
}
|
||||
|
||||
It "Should read fast < 2100 milliseconds".PadRight(90) {
|
||||
It "Should read the simple xlsx in < 2100 milliseconds".PadRight(90) {
|
||||
$timer.TotalMilliseconds | should BeLessThan 2100
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
ConvertFrom-StringData @'
|
||||
SystemDrawingAvaialable=System.Drawing could not be loaded. Color and font look-ups may not be available.
|
||||
SystemDrawingAvailable=System.Drawing could not be loaded. Color and font look-ups may not be available.
|
||||
PS5NeededForPlot=PowerShell 5 is required for plot.ps1
|
||||
ModuleReadyExceptPlot=The ImportExcel moudle is ready, except for that functionality
|
||||
ModuleReadyExceptPlot=The ImportExcel module is ready, except for that functionality
|
||||
'@
|
||||
217
mdHelp/en/ConvertFrom-ExcelSheet.md
Normal file
217
mdHelp/en/ConvertFrom-ExcelSheet.md
Normal file
@@ -0,0 +1,217 @@
|
||||
---
|
||||
external help file: ImportExcel-help.xml
|
||||
Module Name: ImportExcel
|
||||
online version: https://github.com/dfinke/ImportExcel
|
||||
schema: 2.0.0
|
||||
---
|
||||
|
||||
# ConvertFrom-ExcelSheet
|
||||
|
||||
## SYNOPSIS
|
||||
Exports Sheets from Excel Workbooks to CSV files.
|
||||
|
||||
## SYNTAX
|
||||
|
||||
```
|
||||
ConvertFrom-ExcelSheet [-Path] <String> [[-OutputPath] <String>] [[-SheetName] <String>] [[-Encoding] <Encoding>]
|
||||
[[-Extension] <String>] [[-Delimiter] <String>] [[-Property] <Object>] [[-ExcludeProperty] <Object>] [-Append]
|
||||
[[-AsText] <String[]>] [<CommonParameters>]
|
||||
```
|
||||
|
||||
## DESCRIPTION
|
||||
This command provides a convenient way to run Import-Excel @ImportParameters | Select-Object @selectParameters | export-Csv @ ExportParameters
|
||||
It can take the parameters -AsText , as used in Import-Excel, )Properties & -ExcludeProperties as used in Select-Object and
|
||||
-Append, -Delimiter and -Encoding as used in Export-CSV
|
||||
|
||||
|
||||
## EXAMPLES
|
||||
|
||||
### Example 1
|
||||
```powershell
|
||||
PS C:\> ConvertFrom-ExcelSheet Path .\__tests__\First10Races.xlsx -OutputPath .. -AsText GridPosition,date
|
||||
```
|
||||
|
||||
First10Races.xlsx contains information about Motor races. The race date and grid (starting) position are stored with custom formats.
|
||||
The command specifies the path to the file, and the directory to create the output file, and specifies that the columns "GridPosition" and "Date" should be treated as text to preserve their formatting
|
||||
|
||||
### Example 2
|
||||
```powershell
|
||||
PS C:\> ConvertFrom-ExcelSheet Path .\__tests__\First10Races.xlsx -OutputPath .. -AsText "GridPosition" -Property driver, @{n="date"; e={[datetime]::FromOADate($_.Date).tostring("#MM/dd/yyyy#")}} , FinishPosition, GridPosition
|
||||
```
|
||||
|
||||
This uses the same file as example 1. Because the race date has a custom format, it imports as a number,
|
||||
The requirement is to create a CSV file with the Driver, a specially formatted Date, FinishPostion and GridPostion (keeping its custom formatting).
|
||||
The command specifies the path to the file, and the directory to create the output file, specifies that the column "GridPosition" should be treated as text instead of a number, and the output properties should be Driver, a calculated "date" field, FinishPosition and GridPsition. FromOADate converts the dates used by Excel (Days since Jan 1 1900) to a datetime object.
|
||||
|
||||
|
||||
## PARAMETERS
|
||||
|
||||
### -Append
|
||||
Use this parameter to have the export add output to the end of the file. Without this parameter, the command replaces the file contents without warning.
|
||||
|
||||
```yaml
|
||||
Type: SwitchParameter
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: Named
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -AsText
|
||||
AsText allows selected columns to be returned as the text displayed in their cells, instead of their value. (* is supported as a wildcard.)
|
||||
|
||||
```yaml
|
||||
Type: String[]
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 8
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Delimiter
|
||||
Selects , or ; as the delimeter for the exported data - if not specified , is used by default.
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
Accepted values: ;, ,
|
||||
|
||||
Required: False
|
||||
Position: 5
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Encoding
|
||||
Sets the text encoding for the output data file; UTF8 bu default
|
||||
|
||||
|
||||
```yaml
|
||||
Type: Encoding
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 3
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -ExcludeProperty
|
||||
Specifies the properties that to exclude from the export. Wildcards are permitted. This parameter is effective only when the command also includes the Property parameter.
|
||||
|
||||
|
||||
```yaml
|
||||
Type: Object
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 7
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Extension
|
||||
Sets the file extension for the exported data, defaults to CSV
|
||||
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
Accepted values: .txt, .log, .csv
|
||||
|
||||
Required: False
|
||||
Position: 4
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -OutputPath
|
||||
The directory where the output file(s) will be created. The file name(s) will match the name of the workbook page which contained the data.
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 1
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Path
|
||||
The path to the .XLSX file which will be exported.
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: True
|
||||
Position: 0
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -Property
|
||||
Specifies the properties to select. Wildcards are permitted - the default is "*".
|
||||
The value of the Property parameter can be a new calculated property, and follows the same pattern as Select-Item
|
||||
|
||||
```yaml
|
||||
Type: Object
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 6
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### -SheetName
|
||||
The name of a sheet to export, or a regular expression which is used to identify sheets
|
||||
|
||||
```yaml
|
||||
Type: String
|
||||
Parameter Sets: (All)
|
||||
Aliases:
|
||||
|
||||
Required: False
|
||||
Position: 2
|
||||
Default value: None
|
||||
Accept pipeline input: False
|
||||
Accept wildcard characters: False
|
||||
```
|
||||
|
||||
### CommonParameters
|
||||
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
|
||||
|
||||
## INPUTS
|
||||
|
||||
### None
|
||||
|
||||
## OUTPUTS
|
||||
|
||||
### System.Object
|
||||
## NOTES
|
||||
|
||||
## RELATED LINKS
|
||||
Reference in New Issue
Block a user