Powershell - Create a Pivot Table in Excel - excel

I have managed to open and adjust my file so far like this :
$Fichier = "XXXX\McAfeeWin10.csv"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($Fichier)
$WorkSheet = $WorkBook.worksheets.item(1)
$objExcel.Visible = $true
$Range = $worksheet.UsedRange.Cells
$range.NumberFormat = "#"
$WorkSheet.Columns("A:C").AutoFit()
That file has 3 columns and looks like this :
Now all I want to do is create a pivot table with the settings like this :
Column = VerNoyau
Row = DATVer
Values = Poste
How can I do it?
I have found pivot table examples but they are very complex and involve creating the whole file. I'm working on an already existing file so I assume it would be simpler.

Related

How to export a DataTable into an Excel file via Powershell?

I was searching for a simple and fast option to export an existing DataTable-object via Powershell into an Excel file.
At the end I came up with this code. I hope it helps others with same challenge:
# get XML-schema and XML-data from the table:
$schema = [System.IO.StringWriter]::new()
$myTable.WriteXmlSchema($schema)
$data = [System.IO.StringWriter]::new()
$myTable.WriteXml($data)
# start Excel and prepare some objects:
$xls = New-Object -Comobject Excel.Application
$xls.DisplayAlerts = $false
$xls.Visible = $false
$book = $xls.Workbooks.Add()
$sheet = $book.Worksheets[1]
$range = $sheet.Range("A1")
# import the data and save the file:
$map = $book.XmlMaps.Add($schema)
[void]$book.XmlImportXml($data, $map, $true, $range)
$book.SaveAs("c:\temp\test.xlsx", 51)
$xls.Quit()

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

Copying graph from Excel to Word with Powershell

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()

How do you add data into an excel spreadsheet from Powershell?

I am trying to add data into a spreadsheet into Excel from Powershell where in column A, it says "Asset Name" and in Column B it says "Host Name". I will be using a variable name $ServerName that will have data that needs to be written in the second row of these columns ($ServerName = TestServer).
The worksheet name is "Asset Search - Server Required"
The spreadsheet is .xlsx
Can anyone help me with this?
Here is an example for your reference-
$excel = New-Object -ComObject excel.application
$excel.visible = $True
$workbook = $excel.Workbooks.Add()
$workbook.Worksheets.Add()
$Data= $workbook.Worksheets.Item(1)
$Data.Name = 'MySpreadsheet'
$Data.Cells.Item(1,1) = 'Asset Name'
$Data.Cells.Item(1,2) = 'HostName'
# Insert Data
$Data.Cells.Item(3,1) = "MyAssetName"
$Data.Cells.Item(3,2) = "MyHostName"
# Format, save and quit excel
$usedRange = $Data.UsedRange
$usedRange.EntireColumn.AutoFit() | Out-Null
$workbook.SaveAs("C:\MyExcel.xlsx")
$excel.Quit()

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