I have a powershell script to convert an excel spreadsheet into a csv file.
One of the columns within the spreadsheet does not show decimals so in the final CSV output it will say 15, where the actual value is 14.55.
I need to convert the column during script runtime to show 4 decimal places.
I've tried this line but it isn't working for me:
$sheet.columns("H").numberformat = "0.0000"
Any ideas if my line is not right or other ways to do this, thanks.
full script is here:
# Set Folder Paths
$processFolder = "C:\Powershell\Excel\Process\"
$outFolder = "C:\Powershell\In\"
$archiveFolder = "C:\Powershell\Excel\Archive\"
$errorFolder = "C:\Powershell\Excel\Error\"
# Get all .xlsx files in Process folder and loop
$ens = Get-ChildItem $processFolder -filter *.xlsx
foreach($e in $ens)
{
& {
$sourceFile = $processFolder + $e.Basename + ".xlsx"
$outFile = $outFolder + $e.Basename + "_" + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + ".csv"
$archiveFile = $archiveFolder + $e.Basename + "_processed_" + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + ".xlsx"
$errorFile = $errorFolder + $e.Basename + "_error_" + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + ".xlsx"
$excelApplication = New-Object -ComObject Excel.Application
try {
$excelApplication.visible = $false;
$excelApplication.DisplayAlerts = $false
$workbook = $excelApplication.Workbooks.Open($sourceFile)
$sheet = $workbook.Sheets.Item("SUMMARY") # Activate the worksheet
$sheet.columns("H").numberformat = "0.0000" # change formatting of column to show decimals so they appear in CSV file
[void]$sheet.Cells.Item(1, 1).EntireColumn.Delete() # Delete the first column
for ($i=1; $i -le 12; $i++) # Delete the first 12 rows as this is header data
{
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete()
}
$workbook.WorkSheets.item("SUMMARY").Activate()
$workbook.SaveAs($outFile, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV) # save file to csv format
$workbook.Close()
Move-Item -Path $sourceFile -Destination $archiveFile # Archive the Excel File with processing datetime stamp
}
catch {
Copy-Item -Path $sourceFile -Destination $errorFile # Move to Error folder the Excel File with error datetime stamp
}
finally {
$excelApplication.Quit()
}
}
}
#.0000?csvfile nanually?