├── Convert-ExcelSheetToJson.ps1 ├── License.md └── README.md /Convert-ExcelSheetToJson.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Converts an Excel sheet from a workbook to JSON 4 | 5 | .DESCRIPTION 6 | To allow for parsing of Excel Workbooks suitably in PowerShell, this script converts a sheet from a spreadsheet into a JSON file of the same structure as the sheet. 7 | 8 | .PARAMETER InputFile 9 | The Excel Workbook to be converted. Can be FileInfo or a String. 10 | 11 | .PARAMETER OutputFileName 12 | The path to a JSON file to be created. 13 | 14 | .PARAMETER SheetName 15 | The name of the sheet from the Excel Workbook to convert. If only one sheet exists, it will convert that one. 16 | 17 | .EXAMPLE 18 | Convert-ExcelSheetToJson -InputFile MyExcelWorkbook.xlsx 19 | 20 | .EXAMPLE 21 | Get-Item MyExcelWorkbook.xlsx | Convert-ExcelSheetToJson -OutputFileName MyConvertedFile.json -SheetName Sheet2 22 | 23 | .LINK 24 | https://flamingkeys.com/convert-excel-sheet-json-powershell 25 | 26 | .NOTES 27 | Written by: Chris Brown 28 | 29 | Find me on: 30 | * My blog: https://flamingkeys.com/ 31 | * Github: https://github.com/chrisbrownie 32 | 33 | #> 34 | [CmdletBinding()] 35 | Param( 36 | [Parameter( 37 | ValueFromPipeline=$true, 38 | Mandatory=$true 39 | )] 40 | [Object]$InputFile, 41 | 42 | [Parameter()] 43 | [string]$OutputFileName, 44 | 45 | [Parameter()] 46 | [string]$SheetName 47 | ) 48 | 49 | #region prep 50 | # Check what type of file $InputFile is, and update the variable accordingly 51 | if ($InputFile -is "System.IO.FileSystemInfo") { 52 | $InputFile = $InputFile.FullName.ToString() 53 | } 54 | # Make sure the input file path is fully qualified 55 | $InputFile = [System.IO.Path]::GetFullPath($InputFile) 56 | Write-Verbose "Converting '$InputFile' to JSON" 57 | 58 | # If no OutputfileName was specified, make one up 59 | if (-not $OutputFileName) { 60 | $OutputFileName = [System.IO.Path]::GetFileNameWithoutExtension($(Split-Path $InputFile -Leaf)) 61 | $OutputFileName = Join-Path $pwd ($OutputFileName + ".json") 62 | } 63 | # Make sure the output file path is fully qualified 64 | $OutputFileName = [System.IO.Path]::GetFullPath($OutputFileName) 65 | 66 | # Instantiate Excel 67 | $excelApplication = New-Object -ComObject Excel.Application 68 | $excelApplication.DisplayAlerts = $false 69 | $Workbook = $excelApplication.Workbooks.Open($InputFile) 70 | 71 | # If SheetName wasn't specified, make sure there's only one sheet 72 | if (-not $SheetName) { 73 | if ($Workbook.Sheets.Count -eq 1) { 74 | $SheetName = @($Workbook.Sheets)[0].Name 75 | Write-Verbose "SheetName was not specified, but only one sheet exists. Converting '$SheetName'" 76 | } else { 77 | throw "SheetName was not specified and more than one sheet exists." 78 | } 79 | } else { 80 | # If SheetName was specified, make sure the sheet exists 81 | $theSheet = $Workbook.Sheets | Where-Object {$_.Name -eq $SheetName} 82 | if (-not $theSheet) { 83 | throw "Could not locate SheetName '$SheetName' in the workbook" 84 | } 85 | } 86 | Write-Verbose "Outputting sheet '$SheetName' to '$OutputFileName'" 87 | #endregion prep 88 | 89 | 90 | # Grab the sheet to work with 91 | $theSheet = $Workbook.Sheets | Where-Object {$_.Name -eq $SheetName} 92 | 93 | #region headers 94 | # Get the row of headers 95 | $Headers = @{} 96 | $NumberOfColumns = 0 97 | $FoundHeaderValue = $true 98 | while ($FoundHeaderValue -eq $true) { 99 | $cellValue = $theSheet.Cells.Item(1, $NumberOfColumns+1).Text 100 | if ($cellValue.Trim().Length -eq 0) { 101 | $FoundHeaderValue = $false 102 | } else { 103 | $NumberOfColumns++ 104 | $Headers.$NumberOfColumns = $cellValue 105 | } 106 | } 107 | #endregion headers 108 | 109 | # Count the number of rows in use, ignore the header row 110 | $rowsToIterate = $theSheet.UsedRange.Rows.Count 111 | 112 | #region rows 113 | $results = @() 114 | foreach ($rowNumber in 2..$rowsToIterate+1) { 115 | if ($rowNumber -gt 1) { 116 | $result = @{} 117 | foreach ($columnNumber in $Headers.GetEnumerator()) { 118 | $ColumnName = $columnNumber.Value 119 | $CellValue = $theSheet.Cells.Item($rowNumber, $columnNumber.Name).Value2 120 | $result.Add($ColumnName,$cellValue) 121 | } 122 | $results += $result 123 | } 124 | } 125 | #endregion rows 126 | 127 | 128 | $results | ConvertTo-Json | Out-File -Encoding ASCII -FilePath $OutputFileName 129 | 130 | Get-Item $OutputFileName 131 | 132 | # Close the Workbook 133 | $excelApplication.Workbooks.Close() 134 | # Close Excel 135 | [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($excelApplication) -------------------------------------------------------------------------------- /License.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Chris Brown 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Convert-ExcelSheetToJson.ps1 2 | 3 | ## SYNOPSIS 4 | Converts an Excel sheet from a workbook to JSON 5 | 6 | ## SYNTAX 7 | 8 | ``` 9 | Convert-ExcelSheetToJson.ps1 [-InputFile] [[-OutputFileName] ] [[-SheetName] ] 10 | ``` 11 | 12 | ## DESCRIPTION 13 | To allow for parsing of Excel Workbooks suitably in PowerShell, this script converts a sheet from a spreadsheet into a JSON file of the same structure as the sheet. 14 | 15 | ## EXAMPLES 16 | 17 | ### -------------------------- EXAMPLE 1 -------------------------- 18 | ``` 19 | Convert-ExcelSheetToJson -InputFile MyExcelWorkbook.xlsx 20 | ``` 21 | 22 | ### -------------------------- EXAMPLE 2 -------------------------- 23 | ``` 24 | Get-Item MyExcelWorkbook.xlsx | Convert-ExcelSheetToJson -OutputFileName MyConvertedFile.json -SheetName Sheet2 25 | ``` 26 | 27 | ## PARAMETERS 28 | 29 | ### -InputFile 30 | The Excel Workbook to be converted. 31 | Can be FileInfo or a String. 32 | 33 | ```yaml 34 | Type: Object 35 | Parameter Sets: (All) 36 | Aliases: 37 | 38 | Required: True 39 | Position: 1 40 | Default value: None 41 | Accept pipeline input: True (ByValue) 42 | Accept wildcard characters: False 43 | ``` 44 | 45 | ### -OutputFileName 46 | The path to a JSON file to be created. 47 | 48 | ```yaml 49 | Type: String 50 | Parameter Sets: (All) 51 | Aliases: 52 | 53 | Required: False 54 | Position: 2 55 | Default value: None 56 | Accept pipeline input: False 57 | Accept wildcard characters: False 58 | ``` 59 | 60 | ### -SheetName 61 | The name of the sheet from the Excel Workbook to convert. 62 | If only one sheet exists, it will convert that one. 63 | 64 | ```yaml 65 | Type: String 66 | Parameter Sets: (All) 67 | Aliases: 68 | 69 | Required: False 70 | Position: 3 71 | Default value: None 72 | Accept pipeline input: False 73 | Accept wildcard characters: False 74 | ``` 75 | 76 | ## INPUTS 77 | 78 | ## OUTPUTS 79 | 80 | ## NOTES 81 | Written by: Chris Brown 82 | 83 | Find me on: 84 | * My blog: https://flamingkeys.com/ 85 | * Github: https://github.com/chrisbrownie 86 | 87 | ## RELATED LINKS 88 | 89 | [https://flamingkeys.com/convert-excel-sheet-json-powershell](https://flamingkeys.com/convert-excel-sheet-json-powershell) 90 | 91 | --------------------------------------------------------------------------------