Skip to content

Instantly share code, notes, and snippets.

@klinkby
Last active June 3, 2019 17:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klinkby/81b90b20661ec446df50dee40a5e94e3 to your computer and use it in GitHub Desktop.
Save klinkby/81b90b20661ec446df50dee40a5e94e3 to your computer and use it in GitHub Desktop.
Powershell script to read Excel spreadsheet contents
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