将csv导入excel并指定单元格格式

时间:2014-05-29 13:11:31

标签: excel powershell

我正在尝试将多个csv文件导入到1个Excel工作簿中的自己的选项卡中。我有一个问题,长数字段显示为指数数据,并将最后一位数字更改为0.例如,我有一个16位数的帐号(1234567890123456),它在Excel中显示为指数数字(1.23457E + 15) 。当我查看单元格中的实际数字时(1234567890123450)。我假设如果我在将其引入之前制作列文本,它将起作用,但我不确定如何做到这一点。这是我的代码。

$excel = New-Object -ComObject excel.application 
$excel.visible = $False 
$excel.displayalerts=$False 
$workbook = $excel.workbooks.add()
$sheets = $workbook.sheets
$sheetCount = $Sheets.Count
$mySheet = 1
$mySheetName = "Sheet" + $mySheet
$s1 = $sheets | where {$_.name -eq $mySheetName }
$s1.Activate()
If($sheetCount -gt 1)
{
#Delete other Sheets
$Sheets | ForEach
    {
    $tmpSheetName = $_.Name
    $tmpSheet = $_
    If($tmpSheetName -ne "Sheet1"){$tmpSheet.Delete()}
    }
}
#import csv files
$files = dir -Path $csvDir*.csv
ForEach($file in $files){
If($mySheet -gt 1){$s1 = $workbook.sheets.add()}
$s1.Name = $file.BaseName
$s1.Activate()
$s1Data = Import-Csv $file.FullName 
$s1data | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | Clip
$s1.cells.item(1,1).Select()
$s1.Paste()
$mySheet ++
if (test-path $file ) { rm $file }
}

$workbook.SaveAs($excelTMGPath)
$workbook.Close()
$workbook = $null
#$excel.quit() 
while ([System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel)) {}
$excel = $null

1 个答案:

答案 0 :(得分:1)

尝试

如果正确指出$s1

$s1.cells.item(1,1).NumberFormat="@"

如果不起作用,请在必要时使用NumberFormat。使用您喜欢的格式。

将文件扩展名从.csv更改为.txt。在代码中调整文件名

$files = dir -Path $csvDir*.txt