Last 8 used rows in excel. Powershell - excel

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

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.

Comparing all properties of PSCustomObjects (Excel sheet data)

I am working on a script for PowerShell to import data from 2 separate Excel sheets, compare all properties of these sheets and export a new Excel worksheet with this output.
The purpose of this script is to compare an updated excel sheet with a previous version and spot what has changed, what has been added and possibly even what has been removed.
I have been using the Import-Excel module to handle the first part, and Compare-Object for the data comparison.
As far as I can tell Import-Excel imports the Excel data into a System.Object which is a hashtable of PSCustomObjects. Each PSCustomObject corresponds to a row in the Excel sheet.
I am running the following code:
$global:InputdataA = Import-Excel -Path $InputA -WorkSheetname $InputSheetA
$global:InputdataB = Import-Excel -Path $InputB -WorkSheetname $InputSheetB
$global:ReferenceObject = $InputdataA
$global:DifferenceObject = $InputdataB
$global:InputdataHeadersA = $InputdataA[0].psobject.properties.name
$global:InputdataHeadersB = $InputdataB[0].psobject.properties.name
$props = $InputdataHeadersA
$props += $InputdataHeadersB
$props = $props | Select -Unique
$compareResult = Compare-Object -ReferenceObject $ReferenceObject -DifferenceObject $DifferenceObject -Property $props -PassThru -CaseSensitive
I am using 2 excel files for testing:
Personnel_16_12_2018 - small2.xlsx (previous version)
Personnel_28_11_2018 - small2.xlsx (new version with changes and additions)
The files can be downloaded here:
https://ufile.io/bmstu
https://ufile.io/3z62x
The output I would like to see would be only the 7 entries that have been changed/added, with data from difference object (the new version of the excel sheet) This would represent the latest and "correct" data.
Currently I get an output from the compare-object, containing the 7 entries AND the 6 entries that have been changed from the reference object including side-indicator.
Is it possible to make the compare-object return only the changes or do I have to process the output afterwards?
Based on your additional information and the sample files, you could try something like this:
$oldFile = Import-Excel ".\personnel_28_11_2018---small2.xlsx"
$newFile = Import-Excel ".\personnel_16_12_2018---small2.xlsx"
$properties = "TRIAL_PK", "TRIALCOUNTRY_PK", "TRIALSSITE_PK", "ASSIGNMENT_LVL", "ROLE", "INT_EXT", "START_DATA", "END_DATE", "PERSONNELL_PK", "TITLE", "LAST_NAME", "FIRST_NAME", "ORGANIZATION_NAME"
$result = Compare-Object -ReferenceObject $oldFile -DifferenceObject $newFile -Property $properties -PassThru -CaseSensitive | Where-Object {$_.SideIndicator -eq "=>"}
$result | Select-Object $properties | Export-Excel ".\changed.xlsx"

Consolidate excel workbooks data to csv file from folder using power shell

In a folder i have around 20 excel workbooks,each workbook having MIS for upload excel sheet i want to consolidate all data from each workbook from MIS for upload excel sheet to new csv file using powershell
below is the code which i have tried.But i want Browse for a Folder method.
#Get a list of files to copy from
$Files = GCI 'C:\Users\r.shishodia\Desktop\May 2018' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName
#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False
#Open up a new workbook
$Dest = $Excel.Workbooks.Add()
#Loop through files, opening each, selecting the Used range, and only grabbing the first 6 columns of it. Then find next available row on the destination worksheet and paste the data
ForEach($File in $Files[0..20]){
$Source = $Excel.Workbooks.Open($File,$true,$true)
If(($Dest.ActiveSheet.UsedRange.Count -eq 1) -and ([String]::IsNullOrEmpty($Dest.ActiveSheet.Range("A1").Value2))){ #If there is only 1 used cell and it is blank select A1
$Source.WorkSheets.item("MIS for Upload").Activate()
[void]$source.ActiveSheet.Range("A1","R$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
[void]$Dest.Activate()
[void]$Dest.ActiveSheet.Range("A1").Select()
}Else{ #If there is data go to the next empty row and select Column A
$Source.WorkSheets.item("MIS for Upload").Activate()
[void]$source.ActiveSheet.Range("A2","R$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
[void]$Dest.Activate()
[void]$Dest.ActiveSheet.Range("A$(($Dest.ActiveSheet.UsedRange.Rows|Select -last 1).row+1)").Select()
}
[void]$Dest.ActiveSheet.Paste()
$Source.Close()
}
$Dest.SaveAs("C:\Users\r.shishodia\Desktop\Book2.xlsx",51)
$Dest.close()
$Excel.Quit()
For this purpose you could use ImportExcel module - installation guide included in repo README.
Once you install this module you can easily use Import-Excel cmdlet like this:
$Files = GCI 'C:\Users\r.shishodia\Desktop\May 2018' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName
$Temp = #()
ForEach ($File in $Files[0..20]) { # or 19 if you want to have exactly 20 files imported
$Temp += Import-Excel -Path $File -WorksheetName 'MIS for Upload' `
| Select Property0, Property1, Property2, Property3, Property4, Property5
}
To export (you wrote CSV but your destination file format says xlsx):
$Temp | Export-Excel 'C:\Users\r.shishodia\Desktop\Book2.xlsx'
or
$Temp | Export-Csv 'C:\Users\r.shishodia\Desktop\Book2.csv'
That ImportExcel module is really handy ;-)

Powershell - Excel SaveAs csv with specified delimiter

Afternoon all,
Is it possible to save a CSV file using Powershell with a different delimiter, in my case "§". I am using the following script to open and change items in an XLSX file and then wish to save as a "§" delimited CSV. The find and replace method does not work in my case ( (Get-Content -Path $CSVfile).Replace(',','§') | Set-Content -Path $CSVfile2)
$Path = "C:\ScriptRepository\CQC\DataToLoad\"
$FileName = (Get-ChildItem $path).FullName
$FileName2 = (Get-ChildItem $path).Name
$CSVFile = "$Path\$Filename2.csv"
$Excel = New-Object -ComObject Excel.Application -Property #{Visible =
$false}
$Excel.displayalerts=$False
$Workbook = $Excel.Workbooks.Open($FileName)
$WorkSheet = $WorkBook.Sheets.Item(2)
$Worksheet.Activate()
$worksheet.columns.item('G').NumberFormat ="m/d/yyyy"
$Worksheet.Cells.Item(1,3).Value = "Site ID"
$Worksheet.Cells.Item(1,4).Value = "Site Name"
$Worksheet.SaveAs($CSVFile,
[Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVWindows)
$workbook.Save()
$workbook.Close()
$Excel.Quit()
Running the following command, will let you save the CSV file using the delimiter §
Import-CSV filename.csv | ConvertTo-CSV -NoTypeInformation -Delimiter "§" | Out-File output_filename.csv
You should check out ImportExcel - PowerShell module to import/export Excel spreadsheets, without Excel. It makes working with excel files easier using powershell.
I know this is an older post but here is an option I recently came across:
Just update the e:\projects\dss\pse&g.xlsxwith the source location and file as well as the file.csv with the location and file name. Lastly your Worksheet if it is named differently [Sheet1$].
$oleDbConn = New-Object System.Data.OleDb.OleDbConnection
$oleDbCmd = New-Object System.Data.OleDb.OleDbCommand
$oleDbAdapter = New-Object System.Data.OleDb.OleDbDataAdapter
$dataTable = New-Object System.Data.DataTable
$oleDbConn.ConnectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=e:\projects\dss\pse&g.xlsx;Extended Properties=Excel 12.0;Persist Security Info=False"
$oleDbConn.Open()
$oleDbCmd.Connection = $OleDbConn
$oleDbCmd.commandtext = “Select * from [Sheet1$]”
$oleDbAdapter.SelectCommand = $OleDbCmd
$ret=$oleDbAdapter.Fill($dataTable)
Write-Host "Rows returned:$ret" -ForegroundColor green
$dataTable | Export-Csv file.csv -Delimiter ';'
$oleDbConn.Close()
Source
I was using SaveAs(file.csv,6) but couldn't change the delimiter. Also Ishan's resolution works but I wanted something more OOB as this is going to be used within an SSIS package for myself across different systems and this just works. =)

Exporting query result to the excel sheet using powershell

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

Resources