Last active
June 3, 2019 17:35
-
-
Save klinkby/81b90b20661ec446df50dee40a5e94e3 to your computer and use it in GitHub Desktop.
Powershell script to read Excel spreadsheet contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-Spreadsheet { | |
param( | |
[Parameter(Mandatory = $true)] | |
[ValidateScript({ Test-Path $_ -PathType Leaf })] | |
[string]$Path | |
) | |
try { | |
[DocumentFormat.OpenXml.Packaging.SpreadsheetDocument] | Out-Null | |
} | |
catch { | |
# https://www.nuget.org/packages/DocumentFormat.OpenXml | |
Add-Type -LiteralPath (Resolve-Path ".\DocumentFormat.OpenXml.dll") | |
} | |
# open the spreadsheet | |
[DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]$document = [DocumentFormat.OpenXml.Packaging.SpreadsheetDocument]::Open($Path, $false) | |
# get the first sheet | |
[DocumentFormat.OpenXml.Spreadsheet.SheetData]$sheetData = ($document.WorkbookPart.WorksheetParts.RootElement |? { $_.LocalName -eq "sheetData" })[0] | |
# iterate rows | |
[DocumentFormat.OpenXml.OpenXmlElementList]$rows = $sheetData.ChildElements | |
$outRows = @() | |
for ($i=0; $i -lt $rows.Count; $i += 1) { | |
[DocumentFormat.OpenXml.Spreadsheet.Row]$row = $rows.GetItem($i) | |
$outCells = @() | |
# iterate row cells | |
[DocumentFormat.OpenXml.OpenXmlElementList]$cells = $row.ChildElements | |
for ($j=0; $j -lt $cells.Count; $j += 1) { | |
[DocumentFormat.OpenXml.Spreadsheet.Cell]$cell = $cells.GetItem($j) | |
$global:cell = $cell | |
$value = $cell.FirstChild | |
$outCells += ,$value.InnerText | |
} | |
$outRows += ,$outCells | |
} | |
$document.Dispose() | |
return $outRows | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment