简体   繁体   English

Powershell在Excel中缺少前导0

[英]powershell missing leading 0 in excel

I've spent two days troubleshooting why a 4 digit number is being passed through my 5 digit regex. 我花了两天的时间对为什么4位数的数字通过5位数的正则表达式进行故障排除。 When you open the CSV in Excel it shows 4 digits '1234' when you open it in notepad, you'll see '01234'. 在Excel中打开CSV时,在记事本中打开时会显示4位数字“ 1234”,您会看到“ 01234”。 Is there a way to do export-csv in powershell that will maintain the proper format? 有没有办法在powershell中执行export-csv来保持正确的格式? I know the format is related to how Excel thinks it should look like. 我知道格式与Excel认为它的外观有关。 I'm hoping to find a solution in powershell where you force the number format. 我希望在Powershell中找到一种解决方案,您可以在其中强制数字格式。

Is it possible that if the first digit is 0 that you can prepend with special character that will make the first 0 visible in excel? 是否有可能如果第一个数字为0,那么您可以在特殊字符前添加前缀,以使第一个0在excel中可见?

(In case this remains unsolved or can help someone else with this issue) (如果仍然无法解决或可以帮助其他人解决此问题)

Excel's WorkBook.OpenText is helpful here. Excel的WorkBook.OpenText在这里很有帮助。 You can specify the Column Data Type . 您可以指定列数据类型

$xlSession = New-Object -ComObject excel.application

$file = Get-Item "C:\MyDir\MyFile.csv

$xlsession.WorkBooks.OpenText(`
                    $file.FullName,    # Filename
                    2,            # Origin
                    1,            # StartRow
                    1,            # DataType
                    1,            # TextQualifier
                    $false,       # ConsecutiveDelimiter
                    $false,       # Tab
                    $false,       # Semicolon
                    $true,        # Comma
                    $false,       # Space
                    $false,       # Other
                    $false,       # OtherChar


                    # FieldInfo; the important part.
                    # I am telling Excel that columns 1, 2 and 3 are type 2 (Text)
                    # More info: https://msdn.microsoft.com/en-us/library/office/ff193030.aspx

                    @(@(1,2),@(2,2),@(3,2))         

)

$workBook = $xlsession.ActiveWorkbook

$workBook.SaveAs("C:\MyDir\Somefile.xlsx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM