Copying graph from Excel to Word with Powershell - excel

I am trying to copy a graph from excel to word. The source file in excel has two sheets, 'data' & 'graph' on the 'graph' sheet there are 4 graphs, arranged 2x2.
The Word document is empty.
I am fairly new to powershell, but i want to automate a weekly report i have to make. This might seem a little steep, but i like a challenge. Plus, the report eats my time.
This is my code:
$xl = new-object -comobject excel.application
$xl.Visible = $true
$wb = $xl.workbooks.open("H:\Reporting\ULTRAgraphTest.xlsx")
$ws = $wb.worksheets.item(1)
$charts = $ws.ChartObjects()
$chart = $charts.Item(1)
$a = $chart.copy
$wd = new-object -comobject Word.application
$wd.visible = $true
$path = "H:\Reporting\insertest.docx"
$doc = $wd.documents.open($path)
$wd.selection.Paste()
When i run this, the files get opened, but it pastes the clipboard content in the word document. It doesn't seem to copy the graph. What am i not seeing here?

Forgot the partheses
$a = $chart.copy
Should be
$a = $chart.copy()

Related

Load variable data into a workbook using PowerShell

I have an API request that set a variable named $data with CSV style data.
I want to open a Workbook with that data without writing on disk.
How can I do that?
The best I can do is
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add()
$workbook.worksheets(1).Cells(1,1) = $csv
Unfortunately, it fills my CSV into 1 cell, adding delimiter, instead of simply "copying" data into the workbook.
This is a fairly simple task if you want to use the ComObject, as you can use ConvertTo-Csv with a tab delimiter, copy to the clipboard, and paste into Excel. Here's a snippet of what I've used in a script myself to do just that:
$tasks|ConvertTo-Csv -del "`t" -NoTypeInformation|clip
$XL = New-Object -ComObject Excel.Application
$XL.Visible = $true
$WB = $XL.Workbooks.Add()
$XL.ActiveCell.PasteSpecial() | Out-Null

Split Excelfile .xlxs with Powershell based on column values

I need to split and save an excel file based on the values of the first column via a powershell script. Here is how the excel file is build up (app 30.000 rows)
´´´Column1 # Column2 # Column3´´´
´´´AA # data # data # data´´´
´´´AA # data # data # data´´´
´´´AB # data # data # data´´´
´´´AC # data # data # data´´´
´´´AC # data # data # data´´´
The result should be multiple files with filenames AA.xlxs, AB.xlxs, AC.xlxs and of course the according rows data.
What I have so far is the following code:
$objexcel = New-Object -ComObject Excel.Application
$wb = $objexcel.WorkBooks.Open("C:\Test.xlsx")
$objexcel.Visible = $true
$objexcel.DisplayAlerts = $False
$ws = $wb.Worksheets.Item(1)
$doc = $ws.Range("A:A")
foreach ($doc in $docs) {
$newfile,$objexcel = $objexcel.where({$doc -eq $doc})
$newfile | Export-Excel "C:\$doc.xlxs"
}
It just opens the file, but nothing happens.
It would be great if some coder could have a look at the code or provide a working one.
Thanks in advance.
Following is a working code that will iterate through unique elements in column one and make a copy of it in a new spreadsheet and save it.
Function Create-Excel-Spreadsheet {
Param($NameOfSpreadsheet)
# open excel
$excel = New-Object -ComObject excel.application
$excel.visible = $true
# add a worksheet
$workbook = $excel.Workbooks.Add()
$xl_wksht= $workbook.Worksheets.Item(1)
$xl_wksht.Name = $NameOfSpreadsheet
return $workbook
}
$objexcel = New-Object -ComObject Excel.Application
$wb = $objexcel.WorkBooks.Open("C:\Temp\Test.xlsx") # Changing path for test.xlsx file.
$objexcel.Visible = $true
$objexcel.DisplayAlerts = $False
$ws = $wb.Worksheets.Item(1)
$usedRange = $ws.UsedRange
$usedRange.AutoFilter()
$totalRows = $usedRange.Rows.Count
$rangeForUnique = $usedRange.Offset(1, 0).Resize($UsedRange.Rows.Count-1)
[string[]]$UniqueListOfRowValues = $rangeForUnique.Columns.Item(1).Value2 | sort -Unique
for ($i = 0; $i -lt $UniqueListOfRowValues.Count; $i++) {
$newRange = $usedRange.AutoFilter(1, $UniqueListOfRowValues[$i])
$workbook = Create-Excel-Spreadsheet $UniqueListOfRowValues[$i]
$wksheet = $workbook.Worksheets.Item(1)
$range = $ws.UsedRange.Cells
$range.Copy()
$wksheet.Paste($wksheet.Range("A1"))
$workbook.SaveAs("C:\temp\" + $UniqueListOfRowValues[$i], $xlFixedFormat)
$workbook.Close()
}
Reason nothing is happening is because you are iterating over $docs which does not contain any elements. It is currently null.
When you make a reference to look up the data, you are using $objexcel, but thats your excel application.. not the worksheet that you want to iterate over. Use $as for accessing the worksheet.
You need to iterate over Cells of your $ws and take the data when cells.Item(x, 0) and create a new file based on that with values in other two columns.
Link to example on SO -> Create and Update excel file

Excel functions in powershell

I am new to Powershell and I need to parse text file into excel and edit content.
I managed to open file with the following script:
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$Excel.DisplayAlerts = $false
$Excel.Workbooks.OpenText( "Documents\myfile.txt")
It runs without exception, but the data I'm left with tells me the file is not loaded properly.
I need to set parameters like FieldInfo for export.
How do I do this?
Thanks for help.
You have to get the item from the file in order to load it in excel.
DO like this:
$excel = new-object -comobject excel.application
$file = get-item "E:\myfile.txt" # Mention the path of the file
$excel.Visible=$true
$excel.displayalerts = $False
$wb = $excel.workbooks.open($file)
Hope it helps you.
When you bring data into Excel via text file or manual input, Excel will try to interpret what type of data it is, text, date or number. You are bringing in text that looks like a number to Excel.
One solution is to make Powershell do all the work, get it to load the file and then loop through each row. You can then force the format before loading the data.
Something like this:
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$wb = $Excel.Workbooks.add()
$ws = $wb.Worksheets[1]
Import-Csv "Documents\myfile.txt" | % {$i = 1}{
$ws.Range("A" + $i).NumberFormat = '#'
$ws.Range("A" + $i).Value = $_.Field1
#Repeat for each field
$i++
)

Viewing a specific sheet within a workbook using powershell

I have my code for opening and gathering information from any sheet within the workbook, basically what it does it open the workbook, ask what sheet you want to pull info from, and it processes it. It then quits powershell and leaves excel open.
The only problem I have is that I would like powershell to actually show the sheet it is pulling from in the excel window. For instance if I choose sheet 3 to process info from, excel will by default show the last sheet I had selected and leave it, I would like it to go to a specific one. Is there a way to do that?
Yes, it's the Activate() method.
$Excel = new-object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Add()
[void]$Workbook.Worksheets.Add()
[void]$Workbook.Worksheets.Add()
$Workbook.Worksheets.Item(2).Activate()
$Excel.Visible = $true
That will open Excel, create a workbook, add two sheets, and then display the second sheet.
$excel = New-Object -ComObject excel.application
$excel.Visible = $true
$workbook = $excel.workbooks.open('D:\Projects\working\data.xlsm')
$sheet = $workbook.Worksheets.Item('Graph')
$sheet.activate()
$rangeSource=$sheet.range("A50","M73")
$rangeSource.Copy() | out-null
$Results = Get-Clipboard -TextFormatType Html | select -skip 7 | Out-String

Add a column in excel sheet using powershell

I want to add a column after a particular column number in excel sheet using Powershell.
I am able to add it at starting of sheet, but couldn't insert after a specific column.
#This will insert a column at column R
$Excel = New-Object -ComObject excel.application
$ExcelWorkSheet = $ExcelWordBook.Worksheets.Add()
$ExcelWorkSheet.Name = "TestThis"
#do other things
$ColumnSelect = $ExcelWorkSheet.Columns("R:R")
$ColumnSelect.Insert()
Alas, I agree, I have not found neither documentation or examples :-/ .
Nevertheless here is below how to insert a column 7th and give it a name:
(Get-ChildItem "*.xlsb")|
foreach-object {
$xl=New-Object -ComObject Excel.Application
$wb=$xl.workbooks.open($_)
$ws = $wb.worksheets.Item(1)
$ws.Columns.ListObject.ListColumns.Add(7)
$ws.Cells.Item(1,7) ='Comment'
$wb.Save()
$xl.Quit()
while([System.Runtime.Interopservices.Marshal]::ReleaseComObject([System.__ComObject]$xl)){'released'| Out-Null}
}
Best regards

Resources