首页 > 解决方案 > 粘贴\返回到打开的 Excel 工作表的单元格 A1

问题描述

我希望获取在 PowerShell 中生成的字符串并将该字符串粘贴\返回到 OPEN 电子表格的单元格 A:1 中。我对此进行了研究,但我不了解 excel 特定的语法。我是否需要识别和声明正在运行的特定 Excel 工作簿的 PID,如果需要,如何?

我知道如何创建一个新工作簿并将文本添加到单元格 A:1 但不是已经打开的单元格。粘贴后,它还必须“按回车键”执行电子表格功能。

我不知道从哪里开始: ((new-object -com "excel.application").Workbooks.Add()).application.Visible=$True

我在网上搜索过,但没有找到任何有意义的例子。请帮忙

标签: excelpowershell

解决方案


您可以使用以下脚本来实现它

#Specify the path of the excel file
$FilePath = "path\test.xlsx"

#Specify the Sheet name
$SheetName = "Sheet1"

# Create an Object Excel.Application using Com interface
$objExcel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')

# Disable the 'visible' property so the document won't open in excel
$objExcel.Visible = $false

# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)

# Load the WorkSheet 'BuildSpecs'
$WorkSheet = $WorkBook.sheets.item($SheetName)
$WorkSheet.Cells.Item(1,1) = "Link" #Updates the first cell (A1)
$WorkBook.Save()
$WorkBook.Close()

确保该文件具有 PowerShell 脚本的写入权限。

如果要编辑已经打开的工作表,请更改文件的路径并正确提及工作表名称,它将按预期工作。


推荐阅读