Delete first four rows in Excel with Powershell - excel

I have a powershell script that opens an excel file, re-assigns a blank password, and then saves the file. I want to add a task to the script to remove the first 4 rows of the excel file before saving it.

You can't use OleDB for deleting data from Excel document. As per MSDN docmentation:
Although the Jet OLE DB Provider allows you to insert and update
records in an Excel workbook, it does not allow DELETE operation
What you can do is use Exel's COM interface to delete rows. Remember to release COM object too. Like so,
$file = c:\temp\MyExcelFile.xls
# Star Excel, hide window
$excel = new-object -com Excel.Application -Property #{Visible = $false}
$workbook = $excel.Workbooks.Open($file) # Open the file
$sheet = $workbook.Sheets.Item(1) # Activate the first worksheet
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row
$workbook.Close($true) # Close workbook and save changes
$excel.quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) # Release COM

Related

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.

Combining Multiple Workbooks Into One Workbook Worksheet With Powershell

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.

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)

Paste\Return into Cell A1 of open Excel sheet

I wish to take a string generated in PowerShell and paste\return that string into Cell A:1 of an OPEN spreadsheet. I have researched this but I dont understand the excel specific syntax.
Do I need to identify and declare the PID for the specific Excel workbook thats running and if so how?
I know how to create a new workbook and add the text to cell A:1 but not one which is already open. It must also "press return" to execute the spreadsheet functions once pasted.
I dont know where to start other than: ((new-object -com "excel.application").Workbooks.Add()).application.Visible=$True
I have scoured the web but have not found any examples that make sense. Please help
You can achieve it by using the below script
#Specify the path of the excel file
$FilePath = "path\test.xlsx"
#Specify the Sheet name
$SheetName = "Sheet1"
# Create an Object Excel.Application using Com interface
$objExcel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
# Disable the 'visible' property so the document won't open in excel
$objExcel.Visible = $false
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
# Load the WorkSheet 'BuildSpecs'
$WorkSheet = $WorkBook.sheets.item($SheetName)
$WorkSheet.Cells.Item(1,1) = "Link" #Updates the first cell (A1)
$WorkBook.Save()
$WorkBook.Close()
Make sure the file has write permissions from PowerShell scripts.
If you want to edit the sheet which is already open, change the path of the file and mention the sheet name properly and it would work as expected.

Hyperlinks don't copy from Excel to Excel when using Data Connection

I'm an end user who hosts a public Excel 2010 Workbook (without macros, so other users can feel safe) which contains all of the individual player stats for the Madden NFL Mobile game by EA Sports.
I've also created a non-public Macro-Enabled 2010 Workbook which I use to automate the extraction all of the relevant data from a 3rd party website and reparse all of that data into a spreadsheet layout I desire.
My first column of the Macro-Enabled Workbook contains the player's name with a hyperlink to that player's webpage on that 3rd party website, and the macro creates that hyperlink for me just fine.
When I use a Data Connection to automate the syncing of the data from the Macro Book to the Non-Macro Book, everything copies fine, except for the player's name which is only in plain text (no hyperlink).
I also tried to make that first column an excel hyperlink formula (instead of VBA's hyperlink function), but the formula won't transfer via the data connection either.
Is there something I can edit maybe inside of the Data Connection file (.odc) to accomplish my goal?
My only other workaround so far is to add 2 extra hidden columns containing the text link and player name, and then mucking around with the destination Table to make the first column a pre-defined excel HYPERLINK formula to convert the two columns back into a hyperlink.
Any ideas?
Nevermind, I decided to just use a powershell script and batch file to do all of my copy/pasting, and skipping the whole Data Connection thing all together.
My "TransferMaddenData.ps1" PowerShell Code:
$path = "C:\Users\Grego\Desktop\MaddenData.xlsm"
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$Workbook = $Excel.Workbooks.open($path)
$Worksheet = $Workbook.WorkSheets.item("DataOutput")
$Rows = $Worksheet.UsedRange.Rows.Count
$Rows += 1
$Cells = "A3:BD" + $Rows
$Worksheet.activate()
$range = $WorkSheet.Range($Cells)
$range.Copy() | out-null
$path = "C:\Users\Grego\Desktop\Madden1.xlsm"
$Workbook2 = $Excel.Workbooks.open($path)
$Worksheet = $Workbook2.Worksheets.item("Raw Data")
$range = $Worksheet.Range("A3")
$Worksheet.Paste($range)
$Workbook2.Save()
$Workbook.Close()
$Excel.Quit()
Remove-Variable -Name excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
This is my "FixMadden.bat" batch file:
#echo off
color 1F
echo.
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\Users\Grego\Desktop\TransferMaddenData.ps1"
:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL
Hope this maybe helps someone else someday!

Resources