Merge remote-tracking branch 'upstream/master'

This commit is contained in:
DarkLite1
2017-07-25 14:07:32 +02:00
9 changed files with 242 additions and 4 deletions

50
ConvertFromExcelData.ps1 Normal file
View File

@@ -0,0 +1,50 @@
function ConvertFrom-ExcelData {
<#
.SYNOPSIS
Reads data from a sheet, and for each row, calls a custom scriptblock with a list of property names and the row of data.
.EXAMPLE
ConvertFrom-ExcelData .\testSQLGen.xlsx {
param($propertyNames, $record)
$reportRecord = @()
foreach ($pn in $propertyNames) {
$reportRecord += "{0}: {1}" -f $pn, $record.$pn
}
$reportRecord +=""
$reportRecord -join "`r`n"
}
First: John
Last: Doe
The Zip: 12345
....
#>
param(
[Alias("FullName")]
[Parameter(ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true, Mandatory = $true)]
[ValidateScript( { Test-Path $_ -PathType Leaf })]
$Path,
[ScriptBlock]$scriptBlock,
[Alias("Sheet")]
$WorkSheetname = 1,
[int]$HeaderRow = 1,
[string[]]$Header,
[switch]$NoHeader,
[switch]$DataOnly
)
$null = $PSBoundParameters.Remove('scriptBlock')
$params = @{} + $PSBoundParameters
$data = Import-Excel @params
$PropertyNames = $data[0].psobject.Properties |
Where-Object {$_.membertype -match 'property'} |
Select-Object -ExpandProperty name
foreach ($record in $data) {
& $scriptBlock $PropertyNames $record
}
}

View File

@@ -0,0 +1,46 @@
function ConvertFrom-ExcelToSQLInsert {
param(
[Parameter(Mandatory = $true)]
$TableName,
[Alias("FullName")]
[Parameter(ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true, Mandatory = $true)]
[ValidateScript( { Test-Path $_ -PathType Leaf })]
$Path,
[Alias("Sheet")]
$WorkSheetname = 1,
[int]$HeaderRow = 1,
[string[]]$Header,
[switch]$NoHeader,
[switch]$DataOnly
)
$null = $PSBoundParameters.Remove('TableName')
$params = @{} + $PSBoundParameters
ConvertFrom-ExcelData @params {
param($propertyNames, $record)
$ColumnNames = "'" + ($PropertyNames -join "', '") + "'"
$values = foreach ($propertyName in $PropertyNames) { $record.$propertyName }
$targetValues = "'" + ($values -join "', '") + "'"
"INSERT INTO {0} ({1}) Values({2});" -f $TableName, $ColumnNames, $targetValues
}
# $data = Import-Excel @params
# $PropertyNames = $data[0].psobject.Properties |
# Where-Object {$_.membertype -match 'property'} |
# Select-Object -ExpandProperty name
# $ColumnNames = "'" + ($PropertyNames -join "', '") + "'"
# foreach ($record in $data) {
# $values = $(foreach ($propertyName in $PropertyNames) {
# $record.$propertyName
# })
# $targetValues = "'" + ($values -join "', '") + "'"
# "INSERT INTO {0} ({1}) Values({2});" -f $TableName, $ColumnNames, $targetValues
# }
}

53
ConvertToExcelXlsx.ps1 Normal file
View File

@@ -0,0 +1,53 @@
Function ConvertTo-ExcelXlsx {
[CmdletBinding()]
Param
(
[parameter(Mandatory=$true, ValueFromPipeline)]
[string]$Path,
[parameter(Mandatory=$false)]
[switch]$Force
)
Process
{
if(-Not ($Path | Test-Path) ){
throw "File not found"
}
if(-Not ($Path | Test-Path -PathType Leaf) ){
throw "Folder paths are not allowed"
}
$xlFixedFormat = 51 #Constant for XLSX Workbook
$xlsFile = Get-Item -Path $Path
$xlsxPath = "{0}x" -f $xlsFile.FullName
if($xlsFile.Extension -ne ".xls"){
throw "Expected .xls extension"
}
if(Test-Path -Path $xlsxPath){
if($Force){
try {
Remove-Item $xlsxPath -Force
} 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 {
throw "{0} already exists!" -f $xlsxPath
}
}
try{
$Excel = New-Object -ComObject "Excel.Application"
} catch {
throw "Could not create Excel.Application ComObject. Please verify that Excel is installed."
}
$Excel.Visible = $false
$Excel.Workbooks.Open($xlsFile.FullName) | Out-Null
$Excel.ActiveWorkbook.SaveAs($xlsxPath, $xlFixedFormat)
$Excel.ActiveWorkbook.Close()
$Excel.Quit()
}
}

View File

@@ -0,0 +1,13 @@
ConvertFrom-ExcelToSQLInsert People .\testSQLGen.xlsx
ConvertFrom-ExcelData .\testSQLGen.xlsx {
param($propertyNames, $record)
$reportRecord = @()
foreach ($pn in $propertyNames) {
$reportRecord += "{0}: {1}" -f $pn, $record.$pn
}
$reportRecord +=""
$reportRecord -join "`r`n"
}

Binary file not shown.

View File

@@ -4,7 +4,7 @@
RootModule = 'ImportExcel.psm1'
# Version number of this module.
ModuleVersion = '2.3.0'
ModuleVersion = '3.0.1'
# ID used to uniquely identify this module
GUID = '60dd4136-feff-401a-ba27-a84458c57ede'

View File

@@ -20,6 +20,9 @@ Add-Type -Path "$($PSScriptRoot)\EPPlus.dll"
. $PSScriptRoot\TrackingUtils.ps1
. $PSScriptRoot\Copy-ExcelWorkSheet.ps1
. $PSScriptRoot\Set-CellStyle.ps1
. $PSScriptRoot\ConvertFromExcelData.ps1
. $PSScriptRoot\ConvertFromExcelToSQLInsert.ps1
. $PSScriptRoot\ConvertToExcelXlsx.ps1
if($PSVersionTable.PSVersion.Major -ge 5) {
. $PSScriptRoot\plot.ps1

View File

@@ -29,6 +29,9 @@ $targetFiles = echo `
TrackingUtils.ps1 `
Copy-ExcelWorkSheet.ps1 `
Set-CellStyle.ps1 `
ConvertFromExcelToSQLInsert.ps1 `
ConvertFromExcelData.ps1 `
ConvertToExcelXlsx.ps1 `
plot.ps1
Get-ChildItem $targetFiles |

View File

@@ -7,7 +7,7 @@ This PowerShell Module wraps the .NET [EPPlus DLL](http://epplus.codeplex.com/)
Installation
-
####[Powershell V5](https://www.microsoft.com/en-us/download/details.aspx?id=50395) and Later
#### [Powershell V5](https://www.microsoft.com/en-us/download/details.aspx?id=50395) and Later
You can install ImportExcel directly from the Powershell Gallery
* [Recommended] Install to your personal Powershell Modules folder
@@ -19,7 +19,7 @@ Install-Module ImportExcel -scope CurrentUser
Install-Module ImportExcel
```
####Powershell V4 and Earlier
#### Powershell V4 and Earlier
To install to your personal modules folder (e.g. ~\Documents\WindowsPowerShell\Modules), run:
```powershell
@@ -27,6 +27,76 @@ iex (new-object System.Net.WebClient).DownloadString('https://raw.github.com/dfi
```
# What's new
#### 7/3/2017
Thanks to [Mikkel Nordberg](https://www.linkedin.com/in/mikkelnordberg). He contributed a `ConvertTo-ExcelXlsx`. To use it, Excel needs to be installed. I converts older Excel files `xls` to 'xlsx'.
#### 6/15/2017
Huge thank you to [DarkLite1](https://github.com/DarkLite1)! Refactoring of code, adding help, adding features, fixing bugs. Specifically this long outstanding one:
[Export-Excel: Numeric values not correct](https://github.com/dfinke/ImportExcel/issues/168)
It is fantasic to work with and have folks like `DarkLite1` in the community, helping make PowerShells so much better.
A hat to you.
Another shout out to [Damian Reeves](https://twitter.com/DamReev)! His questions turn into great features. He asked can you import and Excel sheet and transform the data into SQL Insert statements. The answer is now yes!
```powershell
ConvertFrom-ExcelToSQLInsert People .\testSQLGen.xlsx
```
```
INSERT INTO People ('First', 'Last', 'The Zip') Values('John', 'Doe', '12345');
INSERT INTO People ('First', 'Last', 'The Zip') Values('Jim', 'Doe', '12345');
INSERT INTO People ('First', 'Last', 'The Zip') Values('Tom', 'Doe', '12345');
INSERT INTO People ('First', 'Last', 'The Zip') Values('Harry', 'Doe', '12345');
INSERT INTO People ('First', 'Last', 'The Zip') Values('Jane', 'Doe', '12345');
```
## Bonus Points
Use the underlying `ConvertFrom-ExcelData` and you can use a scriptblock to transform the data your way.
```powershell
ConvertFrom-ExcelData .\testSQLGen.xlsx {
param($propertyNames, $record)
$reportRecord = @()
foreach ($pn in $propertyNames) {
$reportRecord += "{0}: {1}" -f $pn, $record.$pn
}
$reportRecord +=""
$reportRecord -join "`r`n"
}
```
Prints
```
First: John
Last: Doe
The Zip: 12345
First: Jim
Last: Doe
The Zip: 12345
First: Tom
Last: Doe
The Zip: 12345
First: Harry
Last: Doe
The Zip: 12345
First: Jane
Last: Doe
The Zip: 12345
```
#### 2/2/2017
Thank you to [DarkLite1](https://github.com/DarkLite1) for more updates
* TableName with parameter validation, throws an error when the TableName:
- Starts with something else then a letter
- Is NULL or empty
- Contains spaces
- Numeric parsing now uses `CurrentInfo` to use the system settings
#### 2/14/2017
Big thanks to [DarkLite1](https://github.com/DarkLite1) for some great updates
@@ -471,7 +541,7 @@ Example
* If Pivot table is requested, that sheet becomes the tab selected
#### 4/8/2015
* Implemented exporting data to **named sheets** via the -WorkSheename parameter.
* Implemented exporting data to **named sheets** via the -WorkSheetname parameter.
Examples
-