Merge branch 'master' into master

This commit is contained in:
jhoneill
2018-10-24 17:27:23 +01:00
committed by GitHub
12 changed files with 171 additions and 112 deletions

View File

@@ -1,18 +1,21 @@
Function ConvertTo-ExcelXlsx {
[CmdletBinding()]
<#
.SYNOPSIS
Converts an Excel xls to a xlsx using -ComObject
#>
[CmdletBinding()]
Param
(
[parameter(Mandatory=$true, ValueFromPipeline)]
[parameter(Mandatory = $true, ValueFromPipeline)]
[string]$Path,
[parameter(Mandatory=$false)]
[parameter(Mandatory = $false)]
[switch]$Force
)
Process
{
if(-Not ($Path | Test-Path) ){
throw "File not found"
Process {
if (-Not ($Path | Test-Path) ) {
throw "File not found"
}
if(-Not ($Path | Test-Path -PathType Leaf) ){
if (-Not ($Path | Test-Path -PathType Leaf) ) {
throw "Folder paths are not allowed"
}
@@ -20,26 +23,29 @@ Function ConvertTo-ExcelXlsx {
$xlsFile = Get-Item -Path $Path
$xlsxPath = "{0}x" -f $xlsFile.FullName
if($xlsFile.Extension -ne ".xls"){
if ($xlsFile.Extension -ne ".xls") {
throw "Expected .xls extension"
}
if(Test-Path -Path $xlsxPath){
if($Force){
if (Test-Path -Path $xlsxPath) {
if ($Force) {
try {
Remove-Item $xlsxPath -Force
} catch {
}
catch {
throw "{0} already exists and cannot be removed. The file may be locked by another application." -f $xlsxPath
}
Write-Verbose $("Removed {0}" -f $xlsxPath)
} else {
}
else {
throw "{0} already exists!" -f $xlsxPath
}
}
try{
try {
$Excel = New-Object -ComObject "Excel.Application"
} catch {
}
catch {
throw "Could not create Excel.Application ComObject. Please verify that Excel is installed."
}

View File

@@ -1,3 +1,7 @@
param(
[Switch]$DontCreateZip
)
##
# Used in Appveyor.yml
##
@@ -8,10 +12,12 @@ $PSVersionTable.PSVersion
## Otherwise the EPPlus.dll is in use after the Pester run
$ModuleVersion = (Get-Content -Raw .\ImportExcel.psd1) | Invoke-Expression | ForEach-Object ModuleVersion
$dest = "ImportExcel-{0}-{1}.zip" -f $ModuleVersion, (Get-Date).ToString("yyyyMMddHHmmss")
Compress-Archive -Path . -DestinationPath .\$dest
if (!$DontCreateZip) {
$dest = "ImportExcel-{0}-{1}.zip" -f $ModuleVersion, (Get-Date).ToString("yyyyMMddHHmmss")
Compress-Archive -Path . -DestinationPath .\$dest
}
if ((Get-Module -ListAvailable pester) -eq $null) {
if ($null -eq (Get-Module -ListAvailable pester)) {
Install-Module -Name Pester -Repository PSGallery -Force -Scope CurrentUser
}

View File

@@ -15,7 +15,7 @@ Apple, New York, 1200,700
#Add a pivot table, specify its address to put it on the same sheet, use the data that was just exported set the table style and number format.
#Use the "City" for the row names, and "Product" for the columnnames, and sum both the gross and net values for each City/Product combination; add grand totals to rows and columns.
# activate the sheet and add a pivot chart (defined in a hash table)
Add-PivotTable -Address $excel.Sheet1.Cells["F1"] -SourceWorkSheet $Excel.Sheet1 -SourceRange $Excel.Sheet1.Dimension.Address -PivotTableName "Sales" -PivotTableSyle "Medium12" -PivotNumberFormat "$#,##0.00" `
Add-PivotTable -Address $excel.Sheet1.Cells["F1"] -SourceWorkSheet $Excel.Sheet1 -SourceRange $Excel.Sheet1.Dimension.Address -PivotTableName "Sales" -PivotTableStyle "Medium12" -PivotNumberFormat "$#,##0.00" `
-PivotRows "City" -PivotColumns "Product" -PivotData @{Gross="Sum";Net="Sum"}-PivotTotals "Both" -Activate -PivotChartDefinition @{
Title="Gross and net by city and product";
ChartType="ColumnClustered";

View File

@@ -402,7 +402,17 @@
.EXAMPLE
0..360 | ForEach-Object {[pscustomobject][ordered]@{X=$_; Sinx="=Sin(Radians(x)) "} } | Export-Excel -now -LineChart -AutoNameRange
Creates a line chart showing the value of Sine(x) for values of x between 0 and 360 degrees.
Creates a line chart showing the value of Sine(x) for values of X between 0 and 360 degrees.
.EXAMPLE
>
PS> Invoke-Sqlcmd -ServerInstance localhost\DEFAULT -Database AdventureWorks2014 -Query "select * from sys.tables" -OutputAs DataRows |
Export-Excel -Path .\SysTables_AdventureWorks2014.xlsx -WorksheetName Tables
Runs a query against a SQL Server database and outputs the resulting rows DataRows using the -OutputAs parameter.
The results are then piped to the Export-Excel function.
NOTE: You need to install the SqlServer module from the PowerShell Gallery in oder to get the -OutputAs parameter for the Invoke-Sqlcmd cmdlet.
.LINK
https://github.com/dfinke/ImportExcel
#>

View File

@@ -1,120 +1,120 @@
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ImportExcel.psm1'
# Script module or binary module file associated with this manifest.
RootModule = 'ImportExcel.psm1'
# Version number of this module.
ModuleVersion = '5.3.2'
# Version number of this module.
ModuleVersion = '5.3.4'
# ID used to uniquely identify this module
GUID = '60dd4136-feff-401a-ba27-a84458c57ede'
# ID used to uniquely identify this module
GUID = '60dd4136-feff-401a-ba27-a84458c57ede'
# Author of this module
Author = 'Douglas Finke'
# Author of this module
Author = 'Douglas Finke'
# Company or vendor of this module
CompanyName = 'Doug Finke'
# Company or vendor of this module
CompanyName = 'Doug Finke'
# Copyright statement for this module
Copyright = 'c 2015 All rights reserved.'
# Copyright statement for this module
Copyright = 'c 2015 All rights reserved.'
# Description of the functionality provided by this module
Description = @'
# Description of the functionality provided by this module
Description = @'
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 = ''
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# 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 the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module
# DotNetFrameworkVersion = ''
# Minimum version of Microsoft .NET Framework required by this module
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module
# CLRVersion = ''
# Minimum version of the common language runtime (CLR) required by this module
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# 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 = @()
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# 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 = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# 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 = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module
FunctionsToExport = '*'
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module
# ModuleList = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess
PrivateData = @{
# PSData is module packaging and gallery metadata embedded in PrivateData
# It's for rebuilding PowerShellGet (and PoshCode) NuGet-style packages
# We had to do this because it's the only place we're allowed to extend the manifest
# https://connect.microsoft.com/PowerShell/feedback/details/421837
PSData = @{
# The primary categorization of this module (from the TechNet Gallery tech tree).
Category = "Scripting Excel"
# Private data to pass to the module specified in RootModule/ModuleToProcess
PrivateData = @{
# PSData is module packaging and gallery metadata embedded in PrivateData
# It's for rebuilding PowerShellGet (and PoshCode) NuGet-style packages
# We had to do this because it's the only place we're allowed to extend the manifest
# https://connect.microsoft.com/PowerShell/feedback/details/421837
PSData = @{
# The primary categorization of this module (from the TechNet Gallery tech tree).
Category = "Scripting Excel"
# Keyword tags to help users find this module via navigations and search.
Tags = @("Excel","EPPlus","Export","Import")
# Keyword tags to help users find this module via navigations and search.
Tags = @("Excel", "EPPlus", "Export", "Import")
# The web address of an icon which can be used in galleries to represent this module
#IconUri = "http://pesterbdd.com/images/Pester.png"
# The web address of an icon which can be used in galleries to represent this module
#IconUri = "http://pesterbdd.com/images/Pester.png"
# The web address of this module's project or support homepage.
ProjectUri = "https://github.com/dfinke/ImportExcel"
# The web address of this module's project or support homepage.
ProjectUri = "https://github.com/dfinke/ImportExcel"
# The web address of this module's license. Points to a page that's embeddable and linkable.
LicenseUri = "https://github.com/dfinke/ImportExcel/blob/master/LICENSE.txt"
# The web address of this module's license. Points to a page that's embeddable and linkable.
LicenseUri = "https://github.com/dfinke/ImportExcel/blob/master/LICENSE.txt"
# Release notes for this particular version of the module
#ReleaseNotes = $True
# Release notes for this particular version of the module
#ReleaseNotes = $True
# If true, the LicenseUrl points to an end-user license (not just a source license) which requires the user agreement before use.
# RequireLicenseAcceptance = ""
# If true, the LicenseUrl points to an end-user license (not just a source license) which requires the user agreement before use.
# RequireLicenseAcceptance = ""
# Indicates this is a pre-release/testing version of the module.
IsPrerelease = 'False'
# Indicates this is a pre-release/testing version of the module.
IsPrerelease = 'False'
}
}
}
# HelpInfo URI of this module
# HelpInfoURI = ''
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}

View File

@@ -63,7 +63,7 @@ function Import-Excel {
.DESCRIPTION
The Import-Excel cmdlet creates custom objects from the rows in an Excel worksheet. Each row represents one object. All of this is possible without installing Microsoft Excel and by using the .NET library EPPLus.dll.
By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blanc property name, only columns with column headers will be imported.
By default, the property names of the objects are retrieved from the column headers. Because an object cannot have a blank property name, only columns with column headers will be imported.
If the default behavior is not desired and you want to import the complete worksheet as is, the parameter -NoHeader can be used. In case you want to provide your own property names, you can use the parameter -HeaderName.
@@ -221,7 +221,7 @@ function Import-Excel {
Notice that empty rows and empty columns are not imported.
.EXAMPLE
.EXAMPLE
Import data from an Excel worksheet. One object is created for each row. The property names are provided with the -HeaderName parameter. The import will start from row 2 and empty columns and rows are not imported.
----------------------------------------------------------
@@ -241,6 +241,16 @@ function Import-Excel {
Notice that only 1 object is imported with only 3 properties. Column B and row 2 are empty and have been disregarded by using the switch '-DataOnly'. The property names have been named with the values provided with the parameter '-HeaderName'. Row number 1 with Chuck Norris has not been imported, because we started the import from row 2 with the parameter -StartRow 2.
.EXAMPLE
>
PS> ,(Import-Excel -Path .\SysTables_AdventureWorks2014.xlsx) |
Write-SqlTableData -ServerInstance localhost\DEFAULT -Database BlankDB -SchemaName dbo -TableName MyNewTable_fromExcel -Force
Imports data from an Excel file and pipe the data to the Write-SqlTableData to be INSERTed into a table in a SQL Server database.
The ",( ... )" around the Import-Excel command allows all rows to be imported from the Excel file, prior to pipelining to the Write-SqlTableData cmdlet. This helps prevent a RBAR scenario and is important when trying to import thousands of rows.
The -Force parameter will be ignored if the table already exists. However, if a table is not found that matches the values provided by -SchemaName and -TableName parameters, it will create a new table in SQL Server database. The Write-SqlTableData cmdlet will inherit the column names & datatypes for the new table from the object being piped in.
NOTE: You need to install the SqlServer module from the PowerShell Gallery in oder to get the Write-SqlTableData cmdlet.
.LINK
https://github.com/dfinke/ImportExcel

View File

@@ -29,7 +29,7 @@
Add-PivotTable -PivotTableName Sales -Address $excel.Workbook.Worksheets[1].Cells["F1"] `
-SourceWorkSheet $excel.Workbook.Worksheets[1] -PivotRows City -PivotColumns Product -PivotData @{Gross="Sum";Net="Sum"} `
-PivotNumberFormat "$#,##0.00" -PivotTotals Both -PivotTableSyle Medium12 -PivotChartDefinition $chartdef
-PivotNumberFormat "$#,##0.00" -PivotTotals Both -PivotTableStyle Medium12 -PivotChartDefinition $chartdef
Close-ExcelPackage -show $excel
@@ -74,7 +74,7 @@
#Number format to apply to the data cells in the PivotTable.
[string]$PivotNumberFormat,
#Apply a table style to the PivotTable.
[OfficeOpenXml.Table.TableStyles]$PivotTableSyle,
[OfficeOpenXml.Table.TableStyles]$PivotTableStyle,
#Use a chart definition instead of specifying chart settings one by one.
[Parameter(ParameterSetName='ChartbyDef', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
$PivotChartDefinition,
@@ -198,7 +198,7 @@
if ($PivotTotals -eq "None" -or $PivotTotals -eq "Rows") { $pivotTable.ColumGrandTotals = $false } # Epplus spelling mistake, not mine!
elseif ($PivotTotals -eq "Both" -or $PivotTotals -eq "Columns") { $pivotTable.ColumGrandTotals = $true }
if ($PivotDataToColumn ) { $pivotTable.DataOnRows = $false }
if ($PivotTableSyle) { $pivotTable.TableStyle = $PivotTableSyle}
if ($PivotTableStyle) { $pivotTable.TableStyle = $PivotTableStyle}
}
catch {Write-Warning -Message "Failed adding PivotTable '$pivotTableName': $_"}
}
@@ -230,7 +230,7 @@
function New-PivotTableDefinition {
<#
.Synopsis
Creates PivotTable definitons for Export-Excel
Creates PivotTable definitons for Export-Excel
.Description
Export-Excel allows a single PivotTable to be defined using the parameters -IncludePivotTable, -PivotColumns -PivotRows,
-PivotData, -PivotFilter, -PivotTotals, -PivotDataToColumn, -IncludePivotChart and -ChartType.
@@ -274,7 +274,7 @@ function New-PivotTableDefinition {
#Number format to apply to the data cells in the PivotTable
[string]$PivotNumberFormat,
#Apply a table style to the PivotTable
[OfficeOpenXml.Table.TableStyles]$PivotTableSyle,
[OfficeOpenXml.Table.TableStyles]$PivotTableStyle,
#Use a chart definition instead of specifying chart settings one by one
[Parameter(ParameterSetName='ChartbyDef', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
$PivotChartDefinition,

View File

@@ -53,16 +53,26 @@ Install-Module ImportExcel -scope CurrentUser
Install-Module ImportExcel
```
# What's new
# What's new 5.3.4
- HotFix for parameter PivotTableSyle should be PivotTableStyle https://github.com/dfinke/ImportExcel/issues/453
# What's new 5.3.3
- Thank you to (lazywinadmin)[https://github.com/lazywinadmin] - Expand aliases in examples and elsewhere
- In Export-Excel fixed a bug where -AutoNameRange on pre-existing data included the header in the range.
- In Export-Excel fixed a bug which caused a zero, null, or empty string in a list of simple objects to be skipped.
- In Export-Excel improved the behaviour when a new worksheet is created without data, and Tables etc are added to it.
- In Join-Worksheet: added argument completer to -TitleBackgroundColor and set default for -TitleBackgroundStyle to 'Solid'.
- In Add-Excel chart fixed mis-spelling of "Position"
- In Add-Excel chart, New-ExcelChart, tests and Examples fixed mis-spelling of "Position"
- In Send-SqlDataToExcel: improved robustness of check for no data returned.
- In Set-ExcelColumn: -column can come from the pipeline (supporting an array introduces complications for supporting script blocks); -AutoNameRange no longer requires heading to specified (so you can do 1..10 | Set-ExcelColumn -AutoNameRange ); In Set-ExcelRow: -Row can come from the pipeline
- Improved test coverage (back over 80%).
- Help and example improvements. In "Index - music.ps1" the module for querying the index can be downloaded from PowerShell gallery #requires set to demand it. In SQL+FillColumns+Pivot\example2.ps1 the GetSQL module can be downloaded and #Requires has been set. The F1 results spreadsheet is available from one drive and a link is provided.
- Improved test coverage (back over 80%).
- Help and example improvements. In "Index - music.ps1" the module for querying the index can be downloaded from PowerShell gallery #requires set to demand it. In SQL+FillColumns+Pivot\example2.ps1 the GetSQL module can be downloaded and #Requires has been set. The F1 results spreadsheet is available from one drive and a link is provided.
- Added Azure DevOps continuous integration and badges <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>
# What's new in Release 5.3

View File

@@ -10,8 +10,10 @@ Banana, London , 300, 200
Orange, Paris, 600, 500
Banana, Paris, 300, 200
Apple, New York, 1200,700
"@ | Export-Excel -Path $path -TableStyle Medium13 -tablename "RawData" -ConditionalFormat @{Range="C2:C7"; DataBarColor=([System.Drawing.Color]::Green)} -ExcelChartDefinition @{ChartType="Doughnut";XRange="A2:B7"; YRange="C2:C7"; width=800; } -PivotTableDefinition @{Sales=@{
PivotRows="City"; PivotColumns="Product"; PivotData=@{Gross="Sum";Net="Sum"}; PivotNumberFormat="$#,##0.00"; PivotTotals="Both"; PivotTableSyle="Medium12"; Activate=$true
"@ | Export-Excel -Path $path -TableStyle Medium13 -tablename "RawData" -ConditionalFormat @{Range="C2:C7"; DataBarColor="Green"} -ExcelChartDefinition @{ChartType="Doughnut";XRange="A2:B7"; YRange="C2:C7"; width=800; } -PivotTableDefinition @{Sales=@{
PivotRows="City"; PivotColumns="Product"; PivotData=@{Gross="Sum";Net="Sum"}; PivotNumberFormat="$#,##0.00"; PivotTotals="Both"; PivotTableStyle="Medium12"; Activate=$true
PivotChartDefinition=@{Title="Gross and net by city and product"; ChartType="ColumnClustered"; Column=6; Width=600; Height=360; YMajorUnit=500; YMinorUnit=100; YAxisNumberformat="$#,##0"; LegendPosition="Bottom"}}}
$excel = Open-ExcelPackage $path

View File

@@ -328,7 +328,7 @@ Describe "Table Formatting" {
#test expnading named number formats
Set-ExcelColumn -Worksheet $ws -Column 4 -NumberFormat 'Currency'
Set-ExcelColumn -Worksheet $ws -Column 5 -NumberFormat 'Currency'
$PtDef =New-PivotTableDefinition -PivotTableName Totals -PivotRows Product -PivotData @{"Total"="Sum"} -PivotNumberFormat Currency -PivotTotals None -PivotTableSyle Dark2
$PtDef =New-PivotTableDefinition -PivotTableName Totals -PivotRows Product -PivotData @{"Total"="Sum"} -PivotNumberFormat Currency -PivotTotals None -PivotTableStyle Dark2
Export-excel -ExcelPackage $excel -WorksheetName Hardware -PivotTableDefinition $PtDef
$excel= Open-ExcelPackage -Path $path
$ws1 = $excel.Workbook.Worksheets["Hardware"]

Binary file not shown.

15
azure-pipelines.yml Normal file
View File

@@ -0,0 +1,15 @@
resources:
- repo: self
queue:
name: Hosted VS2017
steps:
- powershell: ./ '.\DoTests.ps1'
displayName: 'PowerShell Script'
- task: ArchiveFiles@2
displayName: 'Archive $(Build.BinariesDirectory)'
trigger:
paths:
exclude:
- README.md