Powershell with Excel - excel

What I need to do is to extract the data in the excel row and output them into different rows on Excel. After that, I will need to use the extracted data and perform certain conditions on the extracted data.
This is my current script:
To open excel and apply the formulas
$excel = New-Object -ComObject excel.application
$filepath = 'D:\testexcel.xlsx'
$workbook = $excel.workbooks.open("$filepath")
$worksheet = $workbook.worksheets.item(1)
$excel.Visible = $true
$rows = $worksheet.range("A1").currentregion.rows.count
$worksheet.range("S1:S$rows").formula = $worksheet.range("S1").formula
Function to find the row, apply the formula and output it
function test123(){
param([string]$test123)
$sourcefile = "D:\testexcel.xlsx"
$sheetname = "abc"
$excel = new-object -comobject excel.application
$excel.Visible = $true
$excelworkbook = $excel.Workbooks.open($sourcefile, 2, $true)
$excelworksheet = $excelworkbook.worksheets.item($sheetname)
$row = 1
$column = 1
$found = $false
while(($excelworksheet.cells.item($row, $column).value() -ne $null) -and($found -eq $false)){
if(($excelworksheet.cells.item($row, $column).value()).toupper() -eq $test123.ToUpper()){
write-host $excelworksheet.cells.item($row, $column).value() $excelworksheet.cells.item($row, $column+1).value(),
$excelworksheet.cells.item($row, $column +2).value() $found = $true
}
$row += 1
}
#close workbook
$excelworkbook.close()
$excel.quit()
}
test123 -test123 "Test123"
Please guide me and tell me if this is the right way to do it... Thanks

Please have a look into the ImportExcel module by Douge Finke. This module has the capability to do what you need.
Get it from PowerShell gallery: Install-Module -Name ImportExcel
Github link: https://github.com/dfinke/ImportExcel
you can then do Get-Help Import-Excel -Examples which has pretty good examples.

Related

Powershell - Filter an Excel File

I would like to add a filter for an Excel file within a PowerShell script.
So "if you find in column D the entry "Listener", make the whole row invisible, so filter it out, so that only rows are shown where no "Listener" occurs.
Can I implement this with PowerShell somehow? I tried but it didn't work.
i tried it with this :
$column = 4 # column D
$filename = "C:\Users\xxxxx\Desktop\Test.XLS"
$criteria = "Listener"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$workbook = $Excel.Workbooks.Open($filename)
$worksheet = $workbook.Worksheets.Item(1)
$usedrange = $worksheet.UsedRange
$usedrange.EntireColumn.AutoFilter()
$usedrange.AutoFilter($column, $criteria)
$worksheet.UsedRange.offset($column,4).EntireLine.Delete()
Thanks!
This should work for you:
$column = 4 # column D
$filename = "C:\Users\xxxxx\Desktop\Test.XLS"
$criteria = "Listener"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$workbook = $Excel.Workbooks.Open($filename)
$worksheet = $workbook.Worksheets.Item(1)
$worksheet.Activate()
# find the number of used rows in the table
$rowMax = $worksheet.UsedRange.Rows.Count
# hide rows that match the criteria
# go from bottom to top
# if your file does not have column headers, use $row -gt 0
for ($row = $rowMax; $row -gt 1; $row--) {
if ($worksheet.Cells.Item($row, $column).Value() -eq $criteria) {
$worksheet.Rows($row).Hidden = $true
}
}
# save and close the workbook
$workbook.Close($true)
# quit Excel and clean up the COM objects from memory
$Excel.Quit()
# IMPORTANT: clean-up used Com objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Edit
I may have misinterpreted your question and instead of hiding the rows that match the criteria like in the code above, all you need is to turn on an Autofilter on column 'D':
$column = 4 # column D
$filename = "C:\Users\xxxxx\Desktop\Test.XLS"
$criteria = "Listener"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$workbook = $Excel.Workbooks.Open($filename)
$worksheet = $workbook.Worksheets.Item(1)
$worksheet.Activate()
# find the number of used rows in the table
$rowMax = $worksheet.UsedRange.Rows.Count
# add the autofilter to to column D
[void]$worksheet.Range("D$(1):D$($rowMax)").AutoFilter(1,"<>$criteria")
# save and close the workbook
$workbook.Close($true)
# quit Excel and clean up the COM objects from memory
$Excel.Quit()
# IMPORTANT: clean-up used Com objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Powershell Excel SaveAs requires confirmation

I use below script to convert bunch of xls files to xlsx.
$folderpath = %tempPath%
$filetype ="*xls"
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
write-host $xlFixedFormat
$excel = New-Object -ComObject excel.application
$excel.visible = $true
Get-ChildItem -Path $folderpath -Include $filetype -recurse |
ForEach-Object `
{
$path = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
"Converting $path"
$workbook = $excel.workbooks.open($_.fullname)
$path += ".xlsx"
$workbook.saveas($path, $xlFixedFormat)
$workbook.close()
}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
It used to work perfectly running on VM.
Unfortunately with changing folder path I realised there are popup windows to confirm saving that didn't come up before and the script gets stuck on that.
Any simple corrections that could prevent that error?
"scriptError": {
"localizedName": "Error",
"value": "Unable to get the SaveAs property of the Workbook class\r\nAt C:\\Users\\~
"variableName": "ScriptError"
}
Here's an example of how I set the path when saving an Excel file using PowerShell. I set the path using a combination of the Get-Location cmdlet, Get-Date cmdlet and the file name, which is stored in a string variable for use when saving the script.
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$htFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlHtml
$Date = get-date -format R
$CurrentLocation = Get-Location
$CurrentDir = Get-location
$Timestamp = get-date -format d
$xlsx = [String] $CurrentLocation + "\MyNewExcelStuff-" + $Timestamp + ".xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.add()
$sheet1 = $workbook.worksheets.Item(1)
$sheet1.name = "Stuff"
$Sheet1.Cells.Item(1,1) = "Reporting Stack Stuff"
$title = $Sheet1.Range("A1:K1")
$title.Select()
$title.MergeCells = $true
$title.VerticalAlignment = -4108 # Centre (vertically) heading
$title.HorizontalAlignment = -4108 # Centre (horizontally) heading
$Title.Interior.ColorIndex = 0
$Excel.ActiveWorkbook.SaveAs($xlsx, $xlFixedFormat)
Start-Sleep -s 2
$Excel.Quit()
$Excel = $Null
You should use $workbook.Close($false).

Split excel sheets without cell formula (links) using PowerShell

I have excel with multiple sheets and I'm trying to split sheets into separate workbooks. Excel sheets are linked between, so when I split them cells will have linked values. Do you have idea how to split excel sheets but paste only values, without formulas?
$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible = $false
$Excel.DisplayAlerts = $false
$filepath ="C:\Users\XX\Documents\2020\XXX_test.xlsx"
$Workbook = $Excel.Workbooks.open($filepath)
$WorkbookName = "test.xlsx"
$output_type = "xlsx"
if ($Workbook.Worksheets.Count -gt 0) {
write-Output "Now processing: $WorkbookName"
$FileFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
$WorkbookName = $filepath -replace ".xlsx", ""
foreach($Worksheet in $Workbook.Worksheets) {
$Worksheet.Copy()
$ExtractedFileName = $WorkbookName + "~~" + $Worksheet.Name + "." + $output_type
$Excel.ActiveWorkbook.SaveAs($ExtractedFileName, $FileFormat)
$Excel.ActiveWorkbook.Close
write-Output "Created file: $ExtractedFileName"
}
}
$Workbook.Close()
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
Stop-Process -Name EXCEL
Remove-Variable Excel
The ImportExcel module makes this easier.
Import-Module ImportExcel
$filepath ="C:\Users\XX\Documents\2020\XXX_test.xlsx"
$output_type = "xlsx"
$sheets = Get-ExcelSheetInfo -Path $filepath
foreach ($sheet in $sheets) {
$ExtractedFileName = "{0}~~{1}.{2}" -f ($filepath -replace '\.xlsx$'),$sheet.Name,$output_type
Import-Excel -Path $sheet.Path -WorkSheetName $sheet.Name |
Export-Excel -Path $ExtractedFileName
}

PowerShell find next empty column in Excel

I need a PowerShell snippet that searches for the next empty column in an Excel sheet.
Every help is appreciated.
I've tried this so far:
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$WorkBook = $Excel.Workbooks.Open("C:\Users\Garry\Desktop\test.xlsx")
$Sheet = $Excel.WorkSheets.Item(1)
$xlLastCell = [Microsoft.Office.Interop.Excel.Constants]::xlLastColumn
$z=1
Do{$z, $z++}until ($Sheet.Column.Item(1, $xlLastCell).Value -eq "")
I tried to loop it so it checks every column if there is a value with the do and until statement, but I always get the error
"It is not possible to call a method for an expression that has the value NULL." The errorstatement refers to the Do until loop.
Change condition from "0" to "$null" and replace $xlLastCell with counter $z:
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$excel = New-Object -ComObject Excel.Application
$excel.visible = $true
$workBook = $excel.Workbooks.Open("C:\Users\Garry\Desktop\test.xlsx")
$workSheet = $excel.WorkSheets.Item(1)
# not needed $xlLastCell = [Microsoft.Office.Interop.Excel.Constants]::xlLastColumn
$z = 1
Do {
$z
}
until ( $workSheet.Cells.Item(1, $z++).Value2 -eq $null )

PowerShell Error Creating XLSX

Okay, I have 6 CSVs each containing one column. For this example, the data from the first CSV is used to create the initial document, and each after that is attempting to save to the document.
#ID
$csvFile = "$path\ID.csv"
$fpath = $Filename
$processes = Import-Csv -Path $csvFile
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$workbook = $Excel.workbooks.add()
$excel.cells.item(1,1) = "ID"
$i = 2
foreach($process in $processes)
{
$excel.cells.item($i,1) = $process.ID
$i++
} #end foreach process
$workbook.saveas($fpath)
$Excel.Quit()
Remove-Variable -Name excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
#SRP
$csvFile = "$path\SRP.csv"
$processes = Import-Csv -Path $csvFile
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$workbook = $Excel.workbooks.add()
$excel.cells.item(1,2) = "SRP"
$i = 2
foreach($process in $processes)
{
$excel.cells.item($i,2) = $process.SRP
$i++
} #end foreach process
$workbook.save($fpath)
$Excel.Quit()
Remove-Variable -Name excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
When I get down to the save line on the second one (#SRP section) I get the following error:
Cannot find an overload for "Save" and the argument count: "1".
At D:\UserAdminScripts\0_Powershell_Test_Scripts\Scripts_For_Lisa\NED Stuff\NED_Reports.ps1:130 char:15
+ $workbook.save <<<< ($fpath)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
If I let the script run after the error, I get the same result for each column.
I'm aware this script isn't clean, because I don't need to close and reopen Excel for each run, but I butchered this script from http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/09/copy-csv-columns-to-an-excel-spreadsheet-by-using-powershell.aspx. The saveas works correctly in the first attempt, it's just the save causing an error.
I find when I break the script, I get a pop-up to confirm whether or not I want to make changes to Book2.xlsx. I tell it yes and I check and Book2 has the 2nd column filled out with the data I wanted as the second column on my original sheet.
Any help is appreciated.
Have a look at the $Workbook object with Get-Member:
Save Method void Save ()
The Save() method doesn't accept any arguments and it's failing to work out what to do with that method and your file name argument.
You Quit the Excel app in the #ID section (thus closing the file) so you need to reopen the file before accessing the workbook and trying to write to it.
Well, it looks like I answered my own question, due to ConanW's inspiration to actually, you know, think critically. The answer to my issue is as follows:
#ID
$csvFile = "$path\ID.csv"
$fpath = $Filename
$processes = Import-Csv -Path $csvFile
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$workbook = $Excel.workbooks.add()
$excel.cells.item(1,1) = "ID"
$i = 2
foreach($process in $processes)
{
$excel.cells.item($i,1) = $process.ID
$i++
} #end foreach process
#SRP
$csvFile = "$path\SRP.csv"
$processes = Import-Csv -Path $csvFile
$excel.cells.item(1,2) = "SRP"
$i = 2
foreach($process in $processes)
{
$excel.cells.item($i,2) = $process.SRP
$i++
} #end foreach process
$workbook.saveas($fpath)
$Excel.Quit()
Remove-Variable -Name excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()

Resources