使用Powershell写入Excel文件

knsnq2tg  于 2023-05-01  发布在  Shell
关注(0)|答案(1)|浏览(154)

我想用PowerShell填充我的Excel文件。只要我只使用数字,代码就可以工作。只要我使用一个单词的变量,代码就不再工作,并出现以下错误。“无法强制转换类型为'System'的对象。String' to type 'System.Int32'.”我试图通过拦截值来捕获错误,如果是文本,则将其转换为字符串。不幸的是,它仍然不起作用。谢谢你的帮助:)

$excelFilePath = "C:\Users\Test\test.xlsx"

$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Open($excelFilePath)
$worksheet = $workbook.Worksheets.Item(1)

$Column = $Worksheet.Columns.Item(2)
$Column.Interior.ColorIndex = 6

$columnCount = 5
$rowCount = 13
$four = "four"

$values = @(
    @(1, 'two', 3, $four, 5),
    @(6, 7, 8, 9, 10),
    @(11, 12, 13, 14, 15),
    @(16, 17, 18, 19, 20),
    @(21, 22, 23, 24, 25),
    @(26, 27, 28, 29, 30),
    @(31, 32, 33, 34, 35),
    @(36, 37, 38, 39, 40),
    @(41, 42, 43, 44, 45),
    @(46, 47, 48, 49, 50),
    @(51, 52, 53, 54, 55),
    @(56, 57, 58, 59, 60),
    @(61, 62, 63, 64, 65)
)

# insert data into table
for ($row = 1; $row -le $rowCount; $row++) {
    for ($col = 1; $col -le $columnCount; $col++) {
        $value = $values[$row - 1][$col - 1]
        $cell = $worksheet.Cells.Item($row, $col)

        if ($value.GetType().Name -eq "Int32") {
            $cell.Value2 = $value
        }
        else {
            $cell.Value2 = [System.Convert]::ToString($value)
        }
    }
}

$Column = $Worksheet.Columns.Item(2) 
$Column.Interior.ColorIndex = 6 

$Workbook.Save()
$Workbook.Close()
$Excel.Quit()

我试着只使用数字,它起作用了。我在“#insert data into table”中尝试了这段代码

#insert data into table
for ($row = 1; $row -le $rowCount; $row++) {
    for ($col = 1; $col -le $columnCount; $col++) {
        $value = $values[$row - 1][$col - 1]
        $cell = $worksheet.Cells.Item($row, $col)
        $cell.Value2 = $value
    }
}
9jyewag0

9jyewag01#

我找到了解决方案:)

# insert data into table
for ($row = 1; $row -le $rowCount; $row++) {
    for ($col = 1; $col -le $columnCount; $col++) {
        $value = $values[$row - 1][$col - 1]

        # Prüfen, ob $value eine Zahl oder ein String ist
        if ($value -is [int] -or $value -is [double]) {
            $cell = $worksheet.Cells.Item($row, $col)
            $cell.Value2 = $value
        }
        else {
            $cell = $worksheet.Cells.Item($row, $col)
            $cell.Value2 = "$value" 
        }
    }
}

相关问题