Combining Multiple Workbooks Into One Workbook Worksheet With Powershell - excel

I have this Powershell script i'm trying to combine multiple workbooks with single sheets onto one workbook with a single sheet and combine them all on the one sheet. I can't get past the fact it keeps telling me there is no file named $destfile and can't be opened. What is the correct syntax for that?
Thanks
$ExcelObject = New-Object -ComObject excel.application
$ExcelObject.visible=$true
$file1 = 'file1location'
$file2 = 'file2location'
$destfile = 'fileI want to saveas afterits compiled'
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb1 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb2 = $xl.workbooks.open($file2, $null, $true)
$wb3 = $xl.workbooks.open($destfile) # open target
$sh1_wb2 = $wb2.sheets.item(1) # first sheet in destination workbook
$sheetToCopy = $wb1.sheets.item('Sheet1') # source sheet to copy
$sheetToCopy.copy($sh1_wb2) # copy source sheet to destination workbook
$wb1.close($false) # close source workbook w/o saving
$wb2.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

You can try to use https://github.com/dfinke/ImportExcel
Export data to csv from multiple worksheets with Import-CSV, then combine those CSV files (i suppose that they have identical rows) and import combined CVS back to excel using Export-CSV... quite simple. and does not require any COM manipulations.

Related

Importing CSV to existing XLSM sheet

I am trying to import a CSV file in to an existing excel sheet. I can get it to work with an .xlsx file, but I can't figure it out with a macro enabled sheet. The reason for the macro enabled sheet, is that I want to be able to use macros, after the data has imported, so I can create a PIVOT table.
I have another powershell script running, collecting users and group information, and I want to create an easy to read excel sheet.
$csv = 'C:\\test\CSV\ADusers.csv'
$extemp = 'C:\test\Temp\WithVBA.xlsm'
$ex = 'C:\test\Pivot.xlsm'
$macro = 'add'
# Adding header to CSV
$filedata = import-csv $csv -Header "UserID,GroupID"
$filedata | Export-csv -Path $csv
# copy temp with VBA to new sheet
Copy-Item -Path $extemp -Destination $ex
# start Excel and open file
$excel = New-Object -comobject Excel.Application
$workbook = $excel.Workbooks.Open($ex)
# Run excel hidden
$excel.Visible = $false
# Import CSV here
# Open excel and run saved macro
$app = $excel.Application
$app.Run($macro)
# Save and close Excel
$workbook.save()
$workbook.close()
$excel.Quit()

Powershell export csv results to multiple sheets in an excel workbook

I run a lot of scans against our AD looking for deficiencies (i.e. users without an email, user ID blank, on-leave but AD account not disabled, etc) and all my results are exported to csv files. I'd like each csv result stored on a sheet in a single excel workbook. I've found a lot of sites showing how to convert a csv to an xls or how to export to a single xls sheet but I can't find anything else meeting my needs. I don't have the ability to import the Import-Excel / Export-Excel modules from the PS gallery. Any suggestions on how I can export 3 CSV files (actually array objects - not sure they need to be exported to CSV first) to three sheets in a workbook?
What I've found so far:
# Create Excel object
$excel = new-object -comobject Excel.Application
# Create a new workbook
$workbook = $excel.workbooks.add()
# Name a worksheet
$workbook.WorkSheets.Item(1).Name = "Users"
# Add data from a csv to the current sheet
$workbook = $excel.workbooks.add(“C:\export_users.csv”)
What I can't figure out is how to add data from additional csv files onto additional sheets in the workbook.
Add another worksheet with another Add().
$excel = New-Object -ComObject Excel.Application
$wb1 = $excel.workbooks.add()
$wb1.WorkSheets.Item(1).Name = 'Users 1'
$wb1.Worksheets.Item(1).Name
$wb1.Worksheets.Count
$wb1.Worksheets.Add() | Out-Null
$wb1.WorkSheets.Item(2).Name = 'Users 2'
$wb1.Worksheets.Item(2).Name
$wb1.Worksheets.Count
I have had some success using the ImportExcel module for PowerShell.

Workbook.SaveAs method is popping Save As dialog box

This was working fine until this weekend, now it's stopped..
I have a powershell script that opens an Excel file as read only, copies a sheet from that file into a new file, then saves the new file to a different location. The script still does all of that, gets to the very end, saves the file to the new location, but now it is opening a "Save as" dialog box, which prevents the script from ever completing. Something change with Powershell? Or the SaveAs method?
# Specify file names/paths
$sourceFile = "C:\source.xlsx"
$exportFile = "C:\export.xlsx"
# Open Excel, hidden/suppress alerts
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$Excel.DisplayAlerts = $false
# Open the source workbook in read-only mode
$sourceWorkbook = $Excel.Workbooks.Open($sourceFile,$null,$true)
# Create a new/blank workbook
$newWorkbook = $Excel.Workbooks.Add()
# Copy sheet from source workbook to new workbook
$sourceWorkbook.Sheets("SheetName").Copy($newWorkbook.Sheets[1])
# Save the new workbook
$newWorkbook.SaveAs($exportFile)

Copy multiple Excel worksheets from multiple workbooks to a new workbook using PowerShell

I have been at this for a while and can't seem to find anything that does exactly what I want. I was working off this post: How to use PowerShell to copy several Excel worksheets and make a new one but it doesn't do exactly what I am looking for. I am attempting to copy all worksheets from multiple workbooks and place them in a new workbook. Ideally, I would like to get the file name from one of the workbooks and use it to name the new file in a new directory.
I have found numerous examples of code that can do this, but there are a couple of key features that I am missing and not sure how to implement them. Here is an example of what I have working now:
$file1 = 'C:\Users\Desktop\TestFolder\PredictedAttritionReport.xlsx' # source's fullpath
$file2 = 'C:\Users\Desktop\TestFolder\AdvisorReport' # destination's fullpath
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item('Report') # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('Report') # source sheet to copy
$sh1_wb1.Name = "DeleteMe$(get-date -Format hhmmss)" #Extremely unlikely to be a duplicate name
$sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook
$sh1_wb1.Delete()
$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel
The problem that I have is that I need this to work, such that I don't have to input the actual file name since those names may be different each time they are created and there may be 3 or 4 files with more than one worksheet, where this example works off of only two named files. Additionally, I would like to be able to copy all worksheets in a file instead of just a single named worksheet, which in this case is 'Report'. The final piece is saving it as a new Excel file rather than overwriting the existing destination file, but I think I can figure that part out.
You could specify parameters when you call the script, and use the specified values in place of the sheet/file names as required. Read about PowerShell Parameters here. Reply if you need more info on how to implement.
This function will copy over sheets from one excel workbook to other.
You can call with Copy-AllExcelSheet command one, it is loaded into memory.
See below in example:
Function Copy-AllExcelSheet()
{
param($TargetXls, $sourceXls)
$xl = new-object -c excel.application
$xl.displayAlerts = $false
$sourceWb = $xl.Workbooks.Open($sourceXls,$true,$false)
$targetWB = $xl.Workbooks.Open($TargetXls)
foreach($nextSheet in $sourceWb.Sheets)
{
$nextSheet.Copy($targetWB.Sheets[1])
}
$sourceWb.close($false)
$targetWB.close($true)
$xl.Quit()
}
#To call the function
Copy-AllExcelSheet "c:\Targetfile.xlsx" "c:\sourceFile.xlsx"

How do I export just one worksheet in Excel to a single htm file?

I'm having trouble saving one worksheet from Excel workbook as a single .htm file.
I know if I open up Excel, open my workbook, select the worksheet I want, and do a "Save As" file type .htm it will work. Every time I code it I get "Hitlist.htm" plus a folder named "Hitlist_files" with all the style sheets, etc. Unfortunately, in powershell it does the "save as" with all the other data and supplemental files (extra folders, styling specifications, etc.)
Help. Code below.
#Create and get my Excel Obj
$excel = New-Object -comobject Excel.Application
$excel.visible=$false
$excel.DisplayAlerts=$false
$UserWorkBook = $excel.Workbooks.Open("e:\hitlist\hitlist.xlsx")
#Select first Sheet
$UserWorksheet = $UserWorkBook.Worksheets.Item(1)
#HitList File name and type
$hitlist = "E:\HitList\Hitlist.htm"
$xlHtml = 44
#Save, close, and clean up
#I tried this too...no go - $UserWorkBook.SaveAs($hitlist,$xlHtml)
$UserWorksheet.SaveAs($hitlist,$xlHtml)
$UserWorkBook.close()
$excel.quit()
$excel = $null
I've adjusted your code to your expectations again, after we clarified some more. In particular, look at any line denoted with #changed-grav for my modifications to your existing code, or the very end (#added-grav) for some additional steps I added to fit the exact specs:
(This was tested fully, and appears to be working exactly as you requested - but I did some modifications for my testing, so let me know if I didn't change a value back that you needed)
#Create and get my Excel Obj
$excel = New-Object -comobject Excel.Application
$excel.visible=$false
$excel.DisplayAlerts=$false
$UserWorkBook = $excel.Workbooks.Open("e:\hitlist\hitlist.xlsx")
#Select first Sheet
$UserWorksheet = $UserWorkBook.Worksheets.Item(1)
#HitList File name and type
$hitlistCSV = "e:\hitlist\hitlist.csv" #changed-grav
$hitlistHTML = "e:\hitlist\hitlist.htm" #changed-grav
$xlCSV = 6 #changed-grav
#Save, close, and clean up
$UserWorksheet.SaveAs($hitlistCSV,$xlCSV) #changed-grav
$UserWorkBook.close()
$excel.quit()
$excel = $null
#new functionality, to import the CSV and then export as HTM
#added-grav START
$htmlData = Get-Content $hitlistCSV | ConvertFrom-CSV | ConvertTo-HTML
Set-Content $hitlistHTML $htmlData
Remove-Item $hitlistCSV
#added-grav END

Resources