powershell - 您不能使用 excel 在 powershell 中调用空值表达式的方法
问题描述
我已经开始用 excel 学习 PowerShell 并遇到空值表达式错误
#open excel application
$x1 = New-Object -comobject excel.application
#open excel to show the result in realtime
$x1.Visible = $true
#open the already existing excel to edit
$test = $x1.Workbooks.Open("C:\Users\tushar.v\OneDrive - HCL Technologies Ltd\Documents\test.xlsx")
#to open a specific worksheet
$test2 = $test.worksheets.Item(1).Activate
$test2.Cells.Item(1,1) = "alphatext"
错误 :
You cannot call a method on a null-valued expression.
At line:9 char:1
+ $test2.Cells.Item(1,1) = "alphatext"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
另外,我没有在 excel 中得到输出
解决方案
首先,我建议使用更好的变量名称,因此在较大的脚本中,每个变量都包含什么内容是很清楚的。$test
并且$test2
不是真正的描述性..
那么对于你所尝试的:
工作表的Activate()
方法不会像您想象的那样返回引用已激活工作表的对象,因此您需要首先在变量中获取工作表对象并使用它来执行 Activate() 方法。
尝试:
# create excel application
$excel = New-Object -comobject excel.application
# open excel to show the result in realtime
$excel.Visible = $true
# open the already existing excel to edit
$workbook = $excel.Workbooks.Open("D:\Test\blah.xlsx")
# get a reference to the first worksheet in the file
$worksheet = $workbook.WorkSheets.Item(1)
# make this worksheet active
$worksheet.Activate()
# and add content to the cell
$worksheet.Cells.Item(1,1) = "alphatext"
最后,创建 COM 对象会消耗内存,因此在您的工作完成后,您需要告诉 Windows 它可以清理这些对象:
# Don't forget to quit Excel when done (after saving perhaps?) and to remove the created COM objects from memory:
$excel.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
推荐阅读
- python - 重复角函数python
- php - 当我尝试在服务器地址上创建目录时,mkdir() 上的 php 警告
- python - 在展平的参数张量上使用 tf.gradients 或 tf.hessians
- database - 恢复 Gramps 损坏的数据库(伯克利数据库)
- kotlin - Kotlin Jackson Mapper 中的类型引用错误
- java - 忽略某些 url 路径,Spring Security
- symfony - Symfony 4 + API Plantform +LexikJWTAuthenticationBundle 坏凭证
- python - Python 3.6.5 urllib 设置路径
- c# - 在 XamarinForms 代码隐藏中的选项卡上设置标题
- angular - 给占位符在Angular 6中选择