1

I need a script to convert Excel data files to a CSV format. I used the following snippet of code. The code works however one of the columns in the data is a percentage and the resulting csv file has a rounded value of the percentages (4.55914% -> 4.56%).

  $extension = ((Split-Path $FilePath -Leaf).Split('.'))[1]
  if($extension -eq "xls" -or $extension -eq "xlsx") {
        Write-Host "Converting to CSV: $FilePath" -ForegroundColor Yellow
        $Excel = New-Object -ComObject Excel.Application
        $wb = $Excel.Workbooks.Open($FilePath, $false, $true)
        
        #$wb.WorkSheets(1).Columns.Item(3).NumberFormat = "Text"
        Write-Host (( $wb.WorkSheets(1).Columns.Item(3).NumberFormat )| Format-List | Out-String)
        
        $fileName = Split-Path $FilePath -Leaf
        $tempFile = Join-Path $tempFilesDir $fileName 
        $FilePath = $tempFile -replace $extension, "csv"
        
        $ws = $wb.Worksheets.Item(1)
        $Excel.DisplayAlerts = $false
        
        $ws.SaveAs($FilePath, 6)
        Write-Host "CSV File Saved: $FilePath" -ForegroundColor Green
        $Excel.Quit()
    } 
    

I tried updating the column's number format first $wb.WorkSheets(1).Columns.Item(3).NumberFormat = "@#.########%" However that threw this error Unable to set the NumberFormat property of the Range class. I tried to solve this error to by adding

$wb.WorkSheets(1).Protect('',0,1,0,0,1,1,1)
$wb.WorkSheets(1).Columns.Item(3).NumberFormat = "@##.######%"

This did not work and gave me the same error. Next, I tried $wb.WorkSheets(1).Columns.Item(3).NumberFormat = "Text" This did not give me an error but instead converted all of my values to T1900xt I have no idea why this would happen.

Are there any other solutions I can try before resorting to looping through the file?

6
  • 2
    Try "0.000000%". Commented May 23, 2023 at 16:23
  • 2
    Unrelated side note. Split-Path has a -Extension parameter. And you can use $extension -in ('.xls','.xlsx') Commented May 23, 2023 at 16:30
  • @BigBen "@0.000000%" gave me to same 'Unable to set the NumberFormat property of the Range class error' Commented May 23, 2023 at 16:32
  • 1
    Why are you using an @? That's not what I suggested. Commented May 23, 2023 at 16:33
  • 1
    @ is the number format for Text. It doesn't belong in numeric formats. Commented May 23, 2023 at 16:36

1 Answer 1

2

Your number format is incorrect:

.NumberFormat = "@##.######%"

The @ denotes the Text format string and does not belong in a numeric format string.

Use:

.NumberFormat = "0.000000%"

You could see this thread for other format options.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.