Friday, 21 November 2008

Validate-DocumentPackage.ps1

#REQUIRES -Version 2
#
Validate-DocumentPackage.ps1
#
Validate an Office XML Package
#
Essentially the C# sample at: http://msdn.microsoft.com/en-us/library/bb497334.aspx
#
Thomas Lee - tfl@psp.co.uk

[System.Reflection.Assembly]
::LoadFile("C:\Program Files (x86)\OpenXMLSDK\1.0.1825\lib\DocumentFormat.OpenXml.dll")

# Create a file that we can destroy
copy c:\foo\xlx1master.xlsx c:\foo\xls1.xlsx

# open the document and display details of doc
$xlsx="c:\foo\xls1.xlsx"
$Doc=[DocumentFormat.OpenXML.Packaging.SpreadsheetDocument]::Open($xlsx,$true)
"Document details"
$doc

# Now Delete the workbook part of the document
$remove=$Doc.DeletePart($Doc.WorkbookPart)

# Validate the package. This will return an exception
#
because of the missing document part.
Try {
$valid=$Doc.Validate($null)
"Document is valid"
}
Catch {
"Document NOT Valid"
"Exception reported:"
$Error[$error.count-1]
$v=0
}

# Close Document
$doc.Close()


This script produces the following output:



# Validate-DocumentPackage.ps1
# Validate an Office XML Package
# Essentially the C# sample at: http://msdn.microsoft.com/en-us/library/bb497334.aspx
# Thomas Lee - tfl@psp.co.uk

[System.Reflection.Assembly]::LoadFile("C:\Program Files (x86)\OpenXMLSDK\1.0.1825\lib\DocumentFormat.OpenXml.dll")

# Create a file that we can destroy
copy c:\foo\xlx1master.xlsx c:\foo\xls1.xlsx

# open the document and display details of doc
$xlsx="c:\foo\xls1.xlsx"
$Doc=[DocumentFormat.OpenXML.Packaging.SpreadsheetDocument]::Open($xlsx,$true)
"Document details"
$doc

# Now Delete the workbook part of the document
$remove=$Doc.DeletePart($Doc.WorkbookPart)

# Validate the package. This will return an exception
# because of the missing document part.
Try {
$valid=$Doc.Validate($null)
"Document is valid"
}
Catch {
"Document NOT Valid"
"Exception reported:"
$Error[$error.count-1]
$v=0
}

# Close Document
$doc.Close()




0 comments: