This commit is contained in:
jhoneill
2019-12-15 22:36:31 +00:00
parent ce8a070673
commit 84140d757a
10 changed files with 346 additions and 266 deletions

View File

@@ -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',
@@ -199,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 = ''

View File

@@ -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()
}

View File

@@ -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

View File

@@ -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()
}

View File

@@ -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]@{

View File

@@ -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]

View File

@@ -0,0 +1,33 @@
[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}"$'
$secondText[1] | should match '^"\w+","\d\d \w{3,} \d{4}","\d","\w+ \w+","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

Binary file not shown.

View File

@@ -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

View 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