Merge remote-tracking branch 'upstream/master'

This commit is contained in:
jhoneill
2019-08-25 18:39:53 +01:00
7 changed files with 267 additions and 48 deletions

View File

@@ -0,0 +1,89 @@
<#
This is an example on how to customize Export-Excel to your liking.
First select a name for your function, in ths example its "Out-Excel" you can even set the name to "Export-Excel".
You can customize the following things:
1. To add parameters to the function define them in "param()", here I added "Preset1" and "Preset2".
The parameters need to be removed after use (see comments and code below).
2. To remove parameters from the function add them to the list under "$_.Name -notmatch", I removed "Now".
3. Add your custom code, here I defined what the Presets do:
Preset1 configure the TableStyle, name the table depending on WorksheetName and FreezeTopRow.
Preset2 will set AutoFilter and add the Title "Daily Report".
(see comments and code below).
#>
Function Out-Excel {
[CmdletBinding(DefaultParameterSetName = 'Default')]
param(
[switch]
${Preset1},
[switch]
${Preset2}
)
DynamicParam {
$paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
foreach ($P in (Get-Command -Name Export-Excel).Parameters.values.where( { $_.Name -notmatch 'Verbose|Debug|Action$|Variable$|Buffer$|Now' })) {
$paramDictionary.Add($P.Name, [System.Management.Automation.RuntimeDefinedParameter]::new( $P.Name, $P.ParameterType, $P.Attributes ) )
}
return $paramDictionary
}
begin {
try {
# Run you custom code here if it need to run before calling Export-Excel.
$PSBoundParameters['Now'] = $true
if ($Preset1) {
$PSBoundParameters['TableStyle'] = 'Medium7'
$PSBoundParameters['FreezeTopRow'] = $true
if ($PSBoundParameters['WorksheetName'] -and -not $PSBoundParameters['TableName']) {
$PSBoundParameters['TableName'] = $PSBoundParameters['WorksheetName'] + '_Table'
}
}
elseif ($Preset2) {
$PSBoundParameters['Title'] = 'Daily Report'
$PSBoundParameters['AutoFilter'] = $true
}
# Remove the extra params we added as Export-Excel will not know what to do with them:
$null = $PSBoundParameters.Remove('Preset1')
$null = $PSBoundParameters.Remove('Preset2')
# The rest of the code was auto generated.
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Export-Excel', [System.Management.Automation.CommandTypes]::Function)
# You can add a pipe after @PSBoundParameters to manipulate the output.
$scriptCmd = { & $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline()
$steppablePipeline.Begin($PSCmdlet)
}
catch {
throw
}
}
process {
try {
$steppablePipeline.Process($_)
}
catch {
throw
}
}
end {
try {
$steppablePipeline.End()
}
catch {
throw
}
}
<#
.ForwardHelpTargetName Export-Excel
.ForwardHelpCategory Function
#>
}

View File

@@ -138,7 +138,7 @@
.PARAMETER Activate .PARAMETER Activate
If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a PivotTable is included it will be the active sheet If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a PivotTable is included it will be the active sheet
.PARAMETER Now .PARAMETER Now
The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "AutoFilter" and "Show", and opens the file immediately. The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "TableName" and "Show", and opens the file immediately.
.PARAMETER NumberFormat .PARAMETER NumberFormat
Formats all values that can be converted to a number to the format specified. Formats all values that can be converted to a number to the format specified.
@@ -418,12 +418,12 @@
.LINK .LINK
https://github.com/dfinke/ImportExcel https://github.com/dfinke/ImportExcel
#> #>
[CmdletBinding(DefaultParameterSetName = 'Now')] [CmdletBinding(DefaultParameterSetName = 'Default')]
[OutputType([OfficeOpenXml.ExcelPackage])] [OutputType([OfficeOpenXml.ExcelPackage])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
Param( Param(
[Parameter(Mandatory = $true, ParameterSetName = "Path", Position = 0)] [Parameter(ParameterSetName = 'Default', Position = 0)]
[String]$Path, [String]$Path,
[Parameter(Mandatory = $true, ParameterSetName = "Package")] [Parameter(Mandatory = $true, ParameterSetName = "Package")]
@@ -473,14 +473,9 @@
else { $true } else { $true }
})] })]
[String]$RangeName, [String]$RangeName,
[ValidateScript( {
if (-not $_) { throw 'Tablename is null or empty.' }
elseif ($_[0] -notmatch '[a-z]') { throw 'Tablename starts with an invalid character.' }
else { $true }
})]
[String]$TableName, $TableName,
[OfficeOpenXml.Table.TableStyles]$TableStyle, [OfficeOpenXml.Table.TableStyles]$TableStyle,
@@ -512,7 +507,7 @@
[ScriptBlock]$CellStyleSB, [ScriptBlock]$CellStyleSB,
#If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified #If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
[switch]$Activate, [switch]$Activate,
[Parameter(ParameterSetName = 'Now')] [Parameter(ParameterSetName = 'Default')]
[Switch]$Now, [Switch]$Now,
[Switch]$ReturnRange, [Switch]$ReturnRange,
#By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected. #By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
@@ -531,13 +526,16 @@
try { try {
$script:Header = $null $script:Header = $null
if ($Append -and $ClearSheet) {throw "You can't use -Append AND -ClearSheet."} if ($Append -and $ClearSheet) {throw "You can't use -Append AND -ClearSheet."}
#if we have no params, or explicit -now, or no path/package. Set a path, and set show/autosize/Autofilter if not set (they maybe passed as $false) $TableName = if ($null -eq $TableName -or ($TableName -is [bool] -and $false -eq $TableName)) { $null } else {[String]$TableName}
if ($PSBoundParameters.Keys.Count -eq 0 -Or $Now -or (-not $Path -and -not $ExcelPackage) ) { if ($PSBoundParameters.Keys.Count -eq 0 -Or $Now -or (-not $Path -and -not $ExcelPackage) ) {
$Path = [System.IO.Path]::GetTempFileName() -replace '\.tmp', '.xlsx' if (-not $PSBoundParameters.ContainsKey("Path")) { $Path = [System.IO.Path]::GetTempFileName() -replace '\.tmp', '.xlsx' }
if (-not $PSBoundParameters.ContainsKey('Show')) {$Show = $true} if (-not $PSBoundParameters.ContainsKey("Show")) { $Show = $true }
if (-not $PSBoundParameters.ContainsKey('AutoSize')) {$AutoSize = $true} if (-not $PSBoundParameters.ContainsKey("AutoSize")) { $AutoSize = $true }
if (-not $PSBoundParameters.ContainsKey('AutoFilter') -and if (-not $PSBoundParameters.ContainsKey("TableName") -and
-not $TableName) {$AutoFilter = $true} -not $PSBoundParameters.ContainsKey("TableStyle") -and
-not $AutoFilter) {
$TableName = ''
}
} }
if ($ExcelPackage) { if ($ExcelPackage) {
$pkg = $ExcelPackage $pkg = $ExcelPackage
@@ -578,7 +576,7 @@
} }
#if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don't do anything with autofilter #if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don't do anything with autofilter
if (-not $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) { if ($null -eq $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) {
$TableName = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1).Name $TableName = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1).Name
$AutoFilter = $false $AutoFilter = $false
} }
@@ -809,7 +807,7 @@
if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName} if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName}
#Allow table to be inserted by specifying Name, or Style or both; only process autoFilter if there is no table (they clash). #Allow table to be inserted by specifying Name, or Style or both; only process autoFilter if there is no table (they clash).
if ($TableName) { if ($null -ne $TableName) {
if ($PSBoundParameters.ContainsKey('TableStyle')) { if ($PSBoundParameters.ContainsKey('TableStyle')) {
Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle
} }

View File

@@ -4,7 +4,7 @@
RootModule = 'ImportExcel.psm1' RootModule = 'ImportExcel.psm1'
# Version number of this module. # Version number of this module.
ModuleVersion = '6.2.2' ModuleVersion = '6.2.4'
# ID used to uniquely identify this module # ID used to uniquely identify this module
GUID = '60dd4136-feff-401a-ba27-a84458c57ede' GUID = '60dd4136-feff-401a-ba27-a84458c57ede'
@@ -16,7 +16,7 @@
CompanyName = 'Doug Finke' CompanyName = 'Doug Finke'
# Copyright statement for this module # Copyright statement for this module
Copyright = 'c 2015 All rights reserved.' Copyright = 'c 2019 All rights reserved.'
# Description of the functionality provided by this module # Description of the functionality provided by this module
Description = @' Description = @'

View File

@@ -7,23 +7,19 @@ If this project helped you reduce the time to get your job done, let me know.
![](https://media.giphy.com/media/hpXxJ78YtpT0s/giphy.gif) ![](https://media.giphy.com/media/hpXxJ78YtpT0s/giphy.gif)
<br/>
<br/> <p>
<br/> <a href="https://www.powershellgallery.com/packages/ImportExcel"><img src="https://img.shields.io/powershellgallery/v/ImportExcel.svg"></a>
<br/> <a href="https://www.powershellgallery.com/packages/ImportExcel"><img src="https://img.shields.io/powershellgallery/dt/ImportExcel.svg"></a>
<p align="center"> <a href="./LICENSE.txt"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg"></a>
<a href="https://ci.appveyor.com/project/dfinke/importexcel/branch/master"><img src="https://ci.appveyor.com/api/projects/status/21hko6eqtpccrkba/branch/master?svg=true"></a>
<a href="https://dougfinke.visualstudio.com/ImportExcel/_build?definitionId=10"><img src="https://dougfinke.visualstudio.com/ImportExcel/_apis/build/status/ImportExcel-CI?branchName=master"></a>
</p> </p>
<p align="center"> |CI System |OS|Status|
<a href="./LICENSE.txt"><img |---|---|---|
src="https://img.shields.io/badge/License-Apache%202.0-blue.svg"></a> |Azure DevOps|Windows|[![Build status](https://dougfinke.visualstudio.com/ImportExcel/_apis/build/status/ImportExcel-CI)](https://dougfinke.visualstudio.com/ImportExcel/_build/latest?definitionId=10)|
<a href="https://www.powershellgallery.com/packages/ImportExcel"><img |Azure DevOps|Windows, Linux, Mac|[![Build Status](https://dougfinke.visualstudio.com/ImportExcel/_apis/build/status/dfinke.ImportExcel?branchName=master)](https://dougfinke.visualstudio.com/ImportExcel/_build/latest?definitionId=20&branchName=master)|
src="https://img.shields.io/powershellgallery/dt/ImportExcel.svg"></a> |Appveyor|Windows|[![Build Status](https://ci.appveyor.com/api/projects/status/21hko6eqtpccrkba/branch/master?svg=true)](https://ci.appveyor.com/project/dfinke/importexcel/branch/master)|
<a href="https://www.powershellgallery.com/packages/ImportExcel"><img
src="https://img.shields.io/powershellgallery/v/ImportExcel.svg"></a>
</p>
<!-- /BADGES --> <!-- /BADGES -->
@@ -37,7 +33,8 @@ This PowerShell Module allows you to read and write Excel files without installi
![](https://raw.githubusercontent.com/dfinke/ImportExcel/master/images/testimonial.png) ![](https://raw.githubusercontent.com/dfinke/ImportExcel/master/images/testimonial.png)
# How to Videos # How to Videos
* [PowerShell Excel Module - ImportExcel](https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5uoqS92stXioZw-u-ze_NtvSo0k0K0kq)
* [PowerShell Excel Module - ImportExcel](https://www.youtube.com/watch?v=fvKKdIzJCws&list=PL5uoqS92stXioZw-u-ze_NtvSo0k0K0kq)
Installation Installation
- -
@@ -53,15 +50,39 @@ Install-Module ImportExcel -scope CurrentUser
Install-Module ImportExcel Install-Module ImportExcel
``` ```
# What's new 6.2.1 # What's new 6.2.4
Sensible parameter defaults, make your life easier and gets things done faster.
- Thank you to [DomRRuggeri](https://github.com/DomRRuggeri) for the initial Out-Excel PR and kicking off the conversation on the improvements.
- Thank you to [ili101](https://github.com/ili101) for refactoring and improving the defaults, and adding the tests for parameters.
- Creates a table, with filtering
- Chooses a `TableStyle`
- Displays the Excel spreadsheet automatically
```powershell
Get-Process | select Company, Name, Handles | Export-Excel
```
![image](./images/ImproveNowDefaults.png)
# What's new 6.2.3
Thank you [jhoneill](https://github.com/jhoneill).
- Refactored copy sheet and added pipe support
- Add `ClearAll` to `Set-ExcelRange`
- Fix broken test & regression for `passwords`
- **Note**: Passwords do not work on `pwsh`. The EPPlus library does not support these dotnet core APIs at this time.
# What's new 6.2.2
- Added requested feature, chart trendlines. - Added requested feature, chart trendlines.
- [Example PowerShell script](https://github.com/dfinke/ImportExcel/blob/master/Examples/Charts/NumberOfVisitors.ps1) - [Example PowerShell script](https://github.com/dfinke/ImportExcel/blob/master/Examples/Charts/NumberOfVisitors.ps1)
![](/images/ChartTrendlines.png) ![](/images/ChartTrendlines.png)
# What's new 6.2.2
- Fixed Import-Excel and relative path issue, added unit tests. - Fixed Import-Excel and relative path issue, added unit tests.
# What's new 6.2.0 # What's new 6.2.0

View File

@@ -975,4 +975,86 @@ Describe ExportExcel {
} }
} }
Context " # Parameters and ParameterSets" {
$Path = "$Env:TEMP\test.xlsx"
Remove-Item -Path $Path -ErrorAction SilentlyContinue
$Processes = Get-Process | Select-Object -first 10 -Property Name, cpu, pm, handles, company
it "Default Set with Path".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Path $Path -PassThru
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
$ExcelPackage.File | Should Be $Path
$Worksheet.Cells['A1'].Value | Should Be 'Name'
$Worksheet.Tables | Should BeNullOrEmpty
$Worksheet.AutoFilterAddress | Should BeNullOrEmpty
}
it "ExcelPackage Set. Path and (ExcelPackage or Now) should throw".PadRight(87) {
$ExcelPackage = Export-Excel -Path $Path -PassThru
{Export-Excel -ExcelPackage $ExcelPackage -Path $Path} | Should Throw 'Parameter set cannot be resolved using the specified named parameters'
{Export-Excel -ExcelPackage $ExcelPackage -Now} | Should Throw 'Parameter set cannot be resolved using the specified named parameters'
$Processes | Export-Excel -ExcelPackage $ExcelPackage
Remove-Item -Path $Path
}
it "If TableName and AutoFilter provided AutoFilter will be ignored".PadRight(87) {
$ExcelPackage = Export-Excel -Path $Path -PassThru -TableName 'Data' -AutoFilter
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
$Worksheet.Tables[0].Name | Should Be 'Data'
$Worksheet.AutoFilterAddress | Should BeNullOrEmpty
}
it "Default Set with Path and TableName with generated name".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Path $Path -PassThru -TableName ''
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
$ExcelPackage.File | Should Be $Path
$Worksheet.Tables[0].Name | Should Be 'Table1'
}
it "Now will use temp Path, set TableName with generated name and AutoSize".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Now -PassThru
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
$ExcelPackage.File | Should BeLike ([IO.Path]::GetTempPath() + '*')
$Worksheet.Tables[0].Name | Should Be 'Table1'
$Worksheet.AutoFilterAddress | Should BeNullOrEmpty
$Worksheet.Column(5).Width | Should BeGreaterThan 9.5
}
it "Now allows override of Path and TableName".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Now -PassThru -Path $Path -TableName:$false
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
$ExcelPackage.File | Should Be $Path
$Worksheet.Tables | Should BeNullOrEmpty
$Worksheet.AutoFilterAddress | Should BeNullOrEmpty
$Worksheet.Column(5).Width | Should BeGreaterThan 9.5
}
<# Mock looks unreliable need to check
Mock -CommandName 'Invoke-Item'
it "Now will Show".PadRight(87) {
$Processes | Export-Excel
Assert-MockCalled -CommandName 'Invoke-Item' -Times 1 -Exactly -Scope 'It'
}
it "Now allows override of Show".PadRight(87) {
$Processes | Export-Excel -Show:$false
Assert-MockCalled -CommandName 'Invoke-Item' -Times 0 -Exactly -Scope 'It'
}
#>
it "Now allows override of AutoSize and TableName to AutoFilter".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Now -PassThru -AutoSize:$false -AutoFilter
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
$Worksheet.Tables | Should BeNullOrEmpty
$Worksheet.AutoFilterAddress | Should Not BeNullOrEmpty
[math]::Round($Worksheet.Column(5).Width, 2) | Should Be 9.14
}
it "Now allows to set TableName".PadRight(87) {
$ExcelPackage = $Processes | Export-Excel -Now -PassThru -TableName 'Data'
$Worksheet = $ExcelPackage.Workbook.Worksheets[1]
$Worksheet.Tables[0].Name | Should Be 'Data'
$Worksheet.AutoFilterAddress | Should BeNullOrEmpty
$Worksheet.Column(5).Width | Should BeGreaterThan 9.5
}
}
} }

View File

@@ -1,15 +1,44 @@
resources: jobs:
- repo: self - job: Build_PS_Win2016
queue: pool:
name: Hosted VS2017 vmImage: vs2017-win2016
steps: steps:
- powershell: ./ '.\DoTests.ps1' - powershell: |
displayName: 'PowerShell Script' .\DoTests.ps1
displayName: 'Run Tests on Windows'
- task: ArchiveFiles@2 - job: Build_PSCore_Ubuntu1604
displayName: 'Archive $(Build.BinariesDirectory)'
pool:
vmImage: ubuntu-16.04
steps:
- script: |
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | sudo tee /etc/apt/sources.list.d/microsoft.list
sudo apt-get update
sudo apt-get install -y powershell
displayName: 'Install PowerShell Core'
- script: |
pwsh -c '.\DoTests.ps1'
displayName: 'Run Tests on Linux'
- job: Build_PSCore_MacOS1013
pool:
vmImage: xcode9-macos10.13
steps:
- script: |
brew update
brew tap caskroom/cask
brew cask install powershell
displayName: 'Install PowerShell Core'
- script: |
pwsh -c '.\DoTests.ps1'
displayName: 'Run Tests on macOS'
trigger: trigger:
paths: paths:
exclude: exclude:
- README.md - README.md

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB