I'm trying to import a CSV file into a newly created Excel worksheet, but haven't been able to utilize existing Q&A here (and elsewhere) to solve this issue.
Also, I'm sure I'm making this WAY more difficult than it should be, so please feel free to correct this bloated code if you see fit:
$varOneSheet = "OneSheet"
$xlsNewFile = New-Object -ComObject Excel.Application
$xlsNewFile.SheetsInNewWorkbook = 3
$xlsNewFile.displayAlerts = $false
$xlsNewFile.Visible = $false
$xlsWorkbook = $xlsNewFile.Workbooks.Add()
$sheetToRename = $xlsNewFile.Sheets.Item("Sheet1")
$sheetToRename.Name = $OneSheet
#this all works below, we need to push the data over to #xlsWorkbook now
$xlsCSVFile = New-Object -ComObject Excel.Application
$xlsCSVFile.displayAlerts = $false
$csvFilename = (".\DATA.CSV")
$xlsCSVFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
$xlsCSVFile.Visible = $true
$tmpSheetTOFile = $xlsWorkbook.Sheets.Item(1)
$tmpWorksheet = $xlsCSVFile.Sheets.Item(1)
#########################above is fine
#########################below should copy into $xlsWorkbook Sheet 1
$tmpWorksheet.Copy($tmpSheetTOFile)
The last line above is the failure point, which yields:
Exception calling "Copy" with "1" argument(s): "Copy method of Worksheet class
failed"
At line:1 char:23
+ $tmpWorksheet.Copy <<<< ($tmpSheetTOFile)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Do I really need to create a separate/temporary workbook? Why was I not able to simply use OpenText on the already Saved/existing Workbook?
EDIT: I used this previous question to get to where I am now, so that's why I'm uncertain as to where the failure point lies. As the answer was accepted and signed-off on.
You're creating two different Excel application instances:
$xlsNewFile = New-Object -ComObject Excel.Application
...
$xlsCSVFile = New-Object -ComObject Excel.Application
Copying only works within the same instance, and using two instances isn't required anyway. Simply remove
$xlsCSVFile = New-Object -ComObject Excel.Application
$xlsCSVFile.displayAlerts = $false
...
$xlsCSVFile.Visible = $true
and change
$xlsCSVFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
...
$tmpWorksheet = $xlsCSVFile.Sheets.Item(1)
...
$tmpWorksheet.Copy($tmpSheetTOFile)
to
$xlsNewFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
...
$xlsNewFile.Workbooks.Item(2).Sheets.Item(1).Copy($tmpSheetTOFile)
Having that said, Excel auto-creates a workbook with a new sheet when it imports a CSV anyway (which is also the reason why OpenText doesn't import a CSV into an existing workbook), so why do you need to copy it to another new workbook in the first place? Normally it would suffice to just save the imported CSV as an Excel workbook. If you require additional sheets you can just add them.
$wsName = 'OneSheet'
$csvFilename = '.\data.csv'
$xlsFilename = '.\data.xlsx'
$xl = New-Object -ComObject 'Excel.Application'
$xl.DisplayAlerts = $false
$xl.Visible = $false
$xl.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
$wb = $xl.Workbooks.Item(1)
$ws = $wb.Sheets.Item(1)
$ws2 = $wb.Sheets.Add([Type]::Missing, $ws)
$ws3 = $wb.Sheets.Add([Type]::Missing, $ws2)
$ws.Name = $wsName
$wb.SaveAs($xlsFilename, 51)
Related
I have an challenge that I need to change on a daily basis in a XLSX document the existing sheet name to a new sheet name and than save it
My script looks like this:
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = new-object -comobject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.name = "Headcount"
$workbook.Save = ($xlspath)
$workbook.Close()
$xldoc.Quit()
I always get this error - even so the file gets save and the name has changed:
C:\CommonUserData\Roger\Test\Test.ps1:8 char:1
+ $workbook.Save = "C:\Users\roger\Test - Test\Daily_Files\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException ```
Does someone have an idea how to solve this or make this a very simple script?
You don't even need the .Save() or .SaveAs() methods for this. Just close the workbook with parameter $true:
$xlspath = "C:\Users\roger\Test - Test\Daily_Files\Testfile.xlsx"
$xldoc = New-Object -ComObject Excel.application
$xldoc.DisplayAlerts = $false
$xldoc.Visible =$false
$workbook = $xldoc.Workbooks.Open($xlspath)
$worksheet = $workbook.worksheets.item(1)
$worksheet.Name = "Headcount"
$workbook.Close($true) # save the updated workbook
$xldoc.Quit()
# Important: remove references to the used COM objects when finished so they don't keep lingering in memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xldoc)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
I have below code:
$excelfile="C:\Users\Administrator\Pictures\unprotect_org - Copy (2)\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile,$false,123)
$wb.Unprotect(123);
$wb.Settings.Password = "";
$wb.Save($excelfile);
$excel.Quit()
I have problem with, PS script is opening ui excel application instead of remove password as without open excel.
Getting below error:
Unable to get the Open property of the Workbooks class
At line:1 char:1
+ $wb = $excel.Workbooks.Open($excelfile,$false,123)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Please help to unprotect excel sheets and workbook using powershell.
Ok, here you go:
To open an Excel workbook with a password, you need to specify that password as the fith parameter on the Workbooks.Open() method:
$password = '123'
$excelfile = "C:\Users\Administrator\Pictures\unprotect_org - Copy (2)\unprotect - Copy (2).xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.Workbooks.Open($excelfile, $false, $false, [Type]::Missing, $password)
# remove the protection from this workbook
$wb.Unprotect($password)
# should not be needed, but does no harm
$wb.Password=$null
# close the workbook and save the changes
$wb.Close($true)
$excel.Quit()
# Important: remove the used COM objects from memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Currently working on a robot where I want to download an excel file from a system, copy paste the contents of the excel file to a word file as an embedded excel table, but the table is wider than the page (it is already in landscape mode). I am using a powershell script in DAS to execute this step. To solve the problem normally, I would simply right-click on the table and use Autofit -> Fit to Window. How do I do this in powershell?
My script is currently like this:
$word = new-object -comobject Word.application
$word.visible = $true
$doc1 = $word.documents.open($destination)
$bookmark1 = $doc1.Bookmarks.Item("FacilitySheet")
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\Users\Pater\Downloads\spreadsheet.xlsx")
$ws = $wb.ActiveSheet
$Range1 = $ws.UsedRange.Cells
$RowCount = $Range1.rows.count
$CopyRange = $ws.Range("A1:O$RowCount").Copy()
$bookmark1.Range.Paste()
To solve this you must set the AutoFitBehavior to the desired value. Please check https://learn.microsoft.com/en-us/office/vba/api/word.table.autofitbehavior for the allowed values and take into account that the values wdAutoFitContent, etc may not be accessed from Powershell, so you must set the raw values (1 for wdAutoFitContent, for example)
$word = new-object -comobject Word.application
$word.visible = $true
$doc1 = $word.documents.open($destination)
$bookmark1 = $doc1.Bookmarks.Item("FacilitySheet")
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("C:\Users\Pater\Downloads\spreadsheet.xlsx")
$ws = $wb.ActiveSheet
$Range1 = $ws.UsedRange.Cells
$RowCount = $Range1.rows.count
$CopyRange = $ws.Range("A1:O$RowCount").Copy()
$bookmark1.Range.Paste()
$bookmark1.Range.AutoFitBehavior(1)
Good Evening everyone,
I have a problem that I am having some issues with and I really need some help. I took two csv files and compared them and converted them to an xls. Now the part I am confused about is how will I be able to take the hyperlinks from Column 1, Row 1 in one excel document and embed them into the text in the other document Column 1, Row2.
is there an easy way to do this? I found the follow link which left me a little confused : https://social.technet.microsoft.com/Forums/scriptcenter/en-US/123d673a-f9a7-4ae6-ae9c-d4ae8ef65015/powershell-excel-how-do-i-create-a-hyperlink-to-a-cell-in-another-sheet-of-the-document?forum=ITCG
I appreciate any guidance and help you can offer.
#Define the file path and sheet name
$FilePath= `enter
code"C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test3.csv"
$FilePath2="C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test3.xls"
$FilePath3="C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test4.xls"
$SheetName="Test3"
$SheetName2="HyperLinks"
#Compare two CSV files to look for matches
$CSV1 = import-csv -path
C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test1.csv
$CSV2 = import-csv -path
C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test2.csv
Compare-Object $CSV1 $CSV2 -property ShoppingList -IncludeEqual | where-
object {$_.SideIndicator -eq "=="}
# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
# Enable the 'visible' property so the document will open in excel
$objExcel.Visible = $true
$objExcel.DisplayAlerts = $False
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
# Load the WorkSheet "Test3"
$WorkSheet = $WorkBook.sheets.item($SheetName)
# Delete data from column
[void]$WorkSheet.Cells.Item(1,2).EntireColumn.Delete()
#Auto fit everything so it looks better
$usedRange = $WorkSheet.UsedRange
$usedRange.EntireColumn.AutoFit() | Out-Null
#Save and convert to XLS
$Workbook.SaveAs("C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test3.xls",1)
$Workbook.Saved = $True
#Load
$excel = New-Object -comobject Excel.Application
$excel.Visible = $True
$workbook = $objExcel.Workbooks.Add()
$workbook.Worksheets.Item($FilePath2).Hyperlinks.Add( `
$workbook.Worksheets.Item($FilePath2).Cells.Item(1,2) , `
"" , $FilePath3, "https://community.spiceworks.com/topic/673034-powers
You can use something like this:
$excel = New-Object -comobject Excel.Application
$excel.Visible = $True
$workbook = $excel.Workbooks.Add()
$workbook.Worksheets.Item(1).Hyperlinks.Add($workbook.Worksheets.Item(1).Cells.Item(1,1) ,"" , "Sheet2!C4", "", "Link to sheet2")
Reference : Hyperlinks.Add Method
Hope it helps
I'm trying to import a .txt file which is comma-separated. It gets imported. But excel doesn't seem to understand that it is, comma-separated. It displays all in the same column.
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.txt'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $false
$xl.Workbooks.OpenText($importcsv)
$xl.DisplayAlerts = $false
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$xl.ActiveWorkbook.SaveAs($wbpath,51)
$xl.Quit()
Any suggestions? Thanks.
You have two options. One, if your file extension is .csv instead of .txt, it would work as is. The second option, make sure you pass $True for the comma-delimiter parameter, like so:
$xl.Workbooks.OpenText($importcsv, 2, 1, 1, 1, $False, $False, $False, $True)
You need to supply more parameters to the OpenText method to get it to see the delimiter.
$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.txt'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $true
$xlWindows=2
$xlDelimited=1
$xlTextQualifierDoubleQuote=1
$StartRow=1
$xl.workbooks.OpenText($importcsv,$xlWindows,$StartRow,$xlDelimited,$xlTextQualifierDoubleQuote,$false,$false,$false,$true)
$xl.ActiveWorkbook.SaveAs($wbpath,51)
$xl.Quit()
See the MSDN reference for full details:
https://msdn.microsoft.com/en-us/library/office/ff837097.aspx
The first $false tells it not to consider consecutive delimiters as one, the next one tells it not to consider Tab as a delimiter, the next $false does the same for semicolon, and the $true tells it to use comma as a delimiter. There are additional delimiter options after that that I have not included as the delimiters are all optional, and you only have to include parameters up to the last relevant one to your needs (setting comma to $true).