Home > OS >  Adding Leading Zeros in .csv file
Adding Leading Zeros in .csv file

Time:04-30

I am trying to create a PowerShell script that adds two leading zeros to all the numbers in a particular column.This script is able to add the two zeros to the column values, but only at the end of the values.

When I change the order of the variables on line 16 to '$zeros $employeeNumber', the 7DigitEmployeeNumber column does not include the leading zeros.

I have tried converting the data type of $zeros and $employeeNumber but have been unable to get the script to add leading zeros to the column values. Any guidance is greatly appreciated!

CodePudding user response:

That's because numbers don't have leading zeros. If you want to pad zeros to the left of the number you have to treat it like a string.

$employeeNumber = 73128
$employeeNumberString = $employeeNumber.ToString()
$paddedEmployeeNumberString = $employeeNumberString.PadLeft(7,'0')

That will leave $paddedEmployeeNumberString with a value of 0073128.

CodePudding user response:

Looking at the images you posted, this is not just about padding numbers with leading zeroes, but mainly that these leading zeroes 'dissapear' when the csv file is opened in Excel.

If you want to have Excel respect those zeroes, write them out in your CSV file prefixed with a TAB character:

"`t{0:D7}" -f 73128

produces 0073128

If you need more total digits, just change {0:D7} into {0:D9} or {0:D25} or..

  • Related