Exporting query result to the excel sheet using powershell - excel

I wrote a function Get-oracleresultDa which have oracle connection properties.Through which I can query my DB.
But,the problem is which I try to export the data to the excel sheet it only returns the result of the second query i.e)no status
and not no type
$results = Get-OracleResultDa -conString $connectionString -sqlString $query
-Verbose
$results | SELECT no, type| Export-CSV "H:\Book2.csv" -Force
$rows++
$results1 = Get-OracleResultDa -conString $connectionString -sqlString
$created -Verbose
$results1 | SELECT no, status| Export-CSV "H:\Book2.csv" -
NoTypeInformation
The below mentioned block was in the first 10 linesof the script
$file="H:\Book2.csv"
$excel = New-Object -ComObject excel.application
#Makes Excel Visable
$excel.Application.Visible = $true
$excel.DisplayAlerts = $false
#Creates Excel workBook
$book = $excel.Workbooks.Add()
#Adds worksheets
#gets the work sheet and Names it
$sheet = $book.Worksheets.Item(1)
$sheet.name = 'Created'
#Select a worksheet
$sheet.Activate() | Out-Null
I have few more query's which also as to be exported

If you use powershell 3.0 or better, you can use -Append modificator
$results = Get-OracleResultDa -conString $connectionString -sqlString $query
-Verbose
$results | SELECT no, type| Export-CSV "H:\Book2.csv" -Force
$rows++
$results1 = Get-OracleResultDa -conString $connectionString -sqlString
$created -Verbose
$results1 | SELECT no, status| Export-CSV "H:\Book2.csv" -
NoTypeInformation -Append

Related

Powershell Text to Column

I have a csv file which contains all data in 1 column.
This is the format,
EPOS SKU QTY ReferenceNr
---- --- --- -----------
717 30735002 1 S04-457312
700 30777125 1 S06-457360
700 25671933 1 S06-457389
716 25672169 1 S09-457296
716 25440683 1 S09-457296
I would like to separate those data into 4 columns with these following headers and save/export to csv or xlsx via powershell script.
Thank you for your help
This should work:
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$inputFile = $PSScriptRoot + '\rawtext.txt'
$csvFile = $PSScriptRoot + '\rawtext.csv'
$excelFile = $PSScriptRoot + '\rawtext.xlsx'
# Create datatable
$dt = New-Object system.Data.DataTable
[void]$dt.Columns.Add('EPOS',[string]::empty.GetType() )
[void]$dt.Columns.Add('SKU',[string]::empty.GetType() )
[void]$dt.Columns.Add('QTY',[string]::empty.GetType() )
[void]$dt.Columns.Add('ReferenceNr',[string]::empty.GetType() )
# loop file
foreach($line in [System.IO.File]::ReadLines($inputFile))
{
if( $line -match '^\d+' ) {
$contentArray = $line -split ' +'
$newRow = $dt.NewRow()
$newRow.EPOS = $contentArray[0]
$newRow.SKU = $contentArray[1]
$newRow.QTY = $contentArray[2]
$newRow.ReferenceNr = $contentArray[3]
[void]$dt.Rows.Add( $newRow )
}
}
# create csv
$dt | Export-Csv $outputFile -Encoding UTF8 -Delimiter ';' -NoTypeInformation
#create excel
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
[void]$excel.Workbooks.Open($csvFile).SaveAs($excelFile, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault)
[void]$excel.Workbooks.Close()
[void]$excel.Quit()
# remove csv
Remove-Item -Path $csvFile -Force | Out-Null
With the Export-Csv instead of Format-Table solved.
$ftr = Get-Content -Path $pathfile |
select -Skip 1 |
ConvertFrom-Csv -Delimiter '|' -Header 'Detail', 'LineNr', 'EPOS', 'SKU',
'SKUName', 'QTY', 'StoreName', 'Contact', 'ReferenceNr' |
Select-Object -Property EPOS, SKU, QTY, ReferenceNr |
Export-Csv -Path $target$ArvName.csv -NoTypeInformation
If your question is regarding Excel... (It is not clear for me)
Just rename the file from *.csv to *.txt and open it on Excel.
On the Text Assistant choose "My data has headers" and "Delimited" and it will be correctly imported with each data on one column. As you ask for.
Later on, save as csv or xlsx.

Delete extra columns of table before exporting to Excel

I have a PowerShell script that runs a few API request and then export information on the test into an excel.
When I create the table to I adds couple column for the results. However when I export the tables via Excel there are a bunch of extra column I don't want.
$ResultsTable = New-Object System.Data.DataTable "ResultsTable"
$RTC1 = New-Object system.Data.DataColumn "Type",([string])
$RTC2 = New-Object system.Data.DataColumn "Endpoint",([string])
$RTC3 = New-Object system.Data.DataColumn "PassRate",([string])
$RTC4 = New-Object system.Data.DataColumn "AvgTime",([string])
$RTC5 = New-Object system.Data.DataColumn "MaxTime",([string])
$RTC6 = New-Object system.Data.DataColumn "AvgSize",([string])
$RTC7 = New-Object system.Data.DataColumn "MaxSize",([string])
$ResultsTable.Columns.Add($RTC1)
$ResultsTable.Columns.Add($RTC2)
$ResultsTable.Columns.Add($RTC3)
$ResultsTable.Columns.Add($RTC4)
$ResultsTable.Columns.Add($RTC5)
$ResultsTable.Columns.Add($RTC6)
$ResultsTable.Columns.Add($RTC7)
$Row = $ResultsTable.NewRow()
$Row.Type = "Direct"
$Row.Endpoint = $Uri
$Row.PassRate = "$PassRate%"
$Row.AvgTime = $AvgTime
$Row.MaxTime = $MaxTime
$Row.AvgSize = $AvgSize
$Row.MaxTime = $MaxSize
$ResultsTable.Rows.Add($Row)
$ResultsTable | Export-Excel -Path ".\Output\Unit\API.Customer.Unit.Tests - $DateTime.xlsx" `
-AutoSize `
-WorksheetName "Results" `
-Title "Results Table" `
-TitleBold `
-BoldTopRow `
-FreezeTopRow
The output of this export looks like:
I only need the Columns A - G. How do I get rid of the other columns?
Either select the columns you want to keep:
$ResultsTable |
Select-Object Type, Endpoint, PassRate, AvgTime, MaxTime, AvgSize, MaxSize |
Export-Excel ...
or remove the columns you don't want to keep:
$ResultsTable |
Select-Object -Property * -Exclude RowError, RowState, Table, ItemArray, HasErrors |
Export-Excel ...
If you know that you're always going to need exactly the columns defined in the table, you could also reference them directly:
$ResultsTable |
Select-Object -Property $ResultsTable.Columns.ColumnName |
Export-Excel ...

Last 8 used rows in excel. Powershell

I've looked all over and I can't seem to find an answer for this. Instead of selecting from A1 to G8, I just want it to select the last 8 USED rows in the import it creates. Not sure what to use here.
$pathtsv = "C:\xxxxxx.mdf"
$pathxlsx = "C:\xxxxxxxxxxxxxx.xlsx"
$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true
$Workbook = $Excel.Workbooks.Open($pathxlsx)
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv)
$temp = $excel.Workbooks.Item(2)
$temp = $temp.Worksheets.Item(1)
$CopyRange = $temp.Range("A1:G8")
$CopyRange.Copy()
Thanks in advance.
I'd recommend using the ImportExcel module by Doug Finke rather than using Excel as a COM Object. Then the Excel document can be easily imported as a PowerShell object which can then be filtered by Select-Object -Last 8 or $ImportedExcelObject[-8..-1] then reexported in what I assume a Tab Delimited format.
Install-Module ImportExcel
$pathtsv = "C:\xxxxxx.mdf"
$pathxlsx = "C:\xxxxxxxxxxxxxx.xlsx"
Import-Excel $pathxlsx | Select-Object -Last 8 | Export-CSV $pathtsv -Delimiter "`t"
Note: The Install-Module command is included by default in PowerShell 5+.
Here is the updated code for going the opposite way from a tsv to a a specific row and column in an Excel document using the Export-Excel cmdlet from the ImportExcel Module.
Install-Module ImportExcel
$pathtsv = 'C:\xxxxxx.mdf'
$templatexls = 'C:\yyyyyyyyyy.xlsx'
$pathxlsx = 'C:\xxxxxxxxxxxxxx.xlsx'
Copy-Item $templatexls $pathxlsx
Import-CSV $pathtsv -Delimiter "`t" | Select-Object -Last 8 | Export-Excel -Path $pathxlsx -WorksheetName 'Sheet1' -Show -StartRow 3 -StartColumn 1 -NoHeader

Finding and adding data in Excel via Powershell

I have a CSV file that has similar products within it and quantities of each product beside it.
Sample from CSV file
Qty Ordered Product/Item Description Top row (header)
7 Product1
3 Product2
5 Product1
3 Product3
I need a method to find all the similar product#s, add up their Quantities, and place the total of each similar product in a new row.
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property
#{
Multiselect = $false # Multiple files can be chosen
Filter = 'Excel (*.csv, *.xlxs)|*.csv;*.xlsx' # Specified file types
}
[void]$FileBrowser.ShowDialog()
$file = $FileBrowser.FileNames;
[Reflection.Assembly]::LoadWithPartialName
("Microsoft.Office.Interop.Excel")|Out-Null
$excel = New-Object Microsoft.Office.Interop.Excel.ApplicationClass
$excel.Visible = $true
$wb = $excel.Workbooks.Open($file)
$ws = $wb.ActiveSheet
$c = $ws.Columns
$c.Item(2).hidden = $true
This code, asks the user to select the csv file, hides useless columns and auto-sizes the important columns as well.
Rather than using Excel as a COM Object you could use Import-CSV and then Group-Object. Then loop through the groups for the information you need.
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property #{
Multiselect = $false # Multiple files can be chosen
Filter = 'Excel (.csv, *.xlxs)|.csv;*.xlsx' # Specified file types
}
[void]$FileBrowser.ShowDialog()
ForEach ($file in $FileBrowser.FileNames) {
$CSV = Import-CSV $file | Add-Member -Name Total -Value 0 -MemberType NoteProperty
$Groups = $CSV | Group-Object "Product/Item Description"
$NewCSV = Foreach ($Group in $Groups) {
$Count = 0
$Group.Group."Qty Ordered" | ForEach-Object {$Count += $_}
Foreach ($value in $CSV) {
If ($value."Product/Item Description" -eq $Group.Name) {
$value.Total = $Count
$value
}
}
}
Export-CSV "$filenew" -NoTypeInformation
}

Return object of a function doesn't export to Excel in PowerShell

I'm using the Export-Excel cmdlet to export the output of a function into Excel. My function is as follows:
function SQLQuery($ServerName, $DBName, $Query)
{
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$ServerName;Database=$DBName;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $Query
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$Output = $DataSet.Tables[0]
$SqlConnection.Close()
return $Output
}
$ResultCost = SQLQuery -ServerName $SName -DBName $DBName -Query (Get-Content -Path $CostQueryPath)
$ResultCost.Table | Export-Excel -Path $ReportPath
The direct output doesn't get exported to Excel so I used $ResultCost.Table to export. However, I see many duplicates being exported (if the result has 10 records, the $ResultCost.Table has 10 to the power of 10 i.e., 100 records). How can I export only the direct output? And how do I remove the last 5 unwanted columns?
If you are trying to export a dataset to a .xlsx file try exporting the rows, not the table.
So instead of $ResultCost.Tables | Export-Excel -Path $ReportPath
Try $ResultCost.Tables.Rows | Export-Excel -Path $ReportPath

Resources