获取项目错误的异常

时间:2014-06-02 18:43:53

标签: excel powershell

我正在循环浏览一些csv文件以导入到excel工作表中。我还有文本文件,其中包含每个csv文件的列号和数字格式。

我正在尝试遍历csv文件并将这些数字格式应用于相应的列,但我遇到一个错误,说明异常在此行​​上获取项目。

$s1.columns.item($colnum).NumberFormat=$numberformat

我不知道如何做到这一点。 这是我的代码:

$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 | Sort-Object -Property CreationTime -Descending
ForEach($file in $files){
If($mySheet -gt 1){$s1 = $workbook.sheets.add()}
$txtName = $file.FullName -replace ".csv", ".txt"
Write-Output "textfile name: "$txtName
$s1.Name = $file.BaseName
$s1.Activate()
$s1Data = Import-Csv $file.FullName 
$s1data | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | Clip
$s1.rows.item(1).Font.Bold=$true
$s1.rows.item(1).VerticalAlignment = -4108
$s1.rows.item(1).HorizontalAlignment = -4108
$s1.rows.item(1).rowHeight = 40
#import column numberformats
$numberformats = Import-Csv $txtName
    foreach ($item in $numberformats)
    {
    $numberformat = $($item.NumberFormat)
    $colnum = $($item.ColumnNumber)
    $s1.columns.item($colnum).NumberFormat=$numberformat
    }
$s1.cells.item(1,1).Select()
$s1.Paste()
$headerRange = $s1.Range("a1","az1")
$headerRange.AutoFilter() | Out-Null
$resize = $s1.UsedRange 
$resize.EntireColumn.AutoFit() | Out-Null 
$s1.cells.item(1,1).Select()
$mySheet ++
if (test-path $file ) { rm $file }
}


$workbook.SaveAs($excelTMGPath)
$workbook.Close()
$workbook = $null
$s1Data = $null
$s1 = $null
$resize = $null
$mySheet = $null
$excel.quit() 
while ([System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel)) {}
$excel = $null

1 个答案:

答案 0 :(得分:0)

尝试将上一行更改为

[int32]$colnum = $($item.ColumnNumber)

我猜你是不小心弄到了一条字符串或者它不喜欢的东西。