首页 > 解决方案 > Powershell获取excel公式结果

问题描述

我在powershell脚本中使用excel COM对象,我想在单元格中插入一个公式(也许格式化单元格,因为它可以是文本格式而不是常规),然后得到公式结果并插入这个结果(作为文本) 在另一个单元格中。

我的问题是我无法将单元格重新格式化为一般格式,因此我只能将公式作为纯文本获取。

到目前为止我已经尝试过:

$elecFormula1 = "=...Some valid and tested formula"
$sheetDest.Cells.Item($dummyCellX, $dummyCellY).NumberFormat = "General" # This throws an error
$sheetDest.Cells.Item($dummyCellX, $dummyCellY).Formula = $elecFormula1
$key = "" + $sheetDest.Cells.Item($dummyCellX, $dummyCellY).Value2
$sheetDest.Cells.Item($i, 2) = $key

标签: excelpowershellcom

解决方案


这应该可以解决问题:

Add-Type -AssemblyName Microsoft.Office.Interop.Excel

$excel               = New-Object -ComObject Excel.Application
$excel.Visible       = $True
$excel.DisplayAlerts = $False 

$workbook            = $excel.Workbooks.Open( "C:\Users\myUser\Desktop\test.xlsx", [System.Type]::Missing, $false ) 

$worksheet = $workbook.WorkSheets.item(1)
[void]$worksheet.activate()

$worksheet.Range("A1").NumberFormat = ""
$worksheet.Range("A1").NumberFormat = $worksheet.Range("A1").NumberFormatLocal # "General" or "Standard"
$worksheet.Range("A1").Formula = "=1+1"

$result = $worksheet.Range("A1").value2

$result

[void]$workbook.Close( $false ) 
[void]$excel.Quit() 

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null

推荐阅读