2016-08-12 63 views
0

我試圖將我的文本文件的內容插入Sheet1上的單元格A1,但我所獲得的是插入的文件名而不是文本文件的內容。使用PowerShell將文本從文本文件插入到現有的Excel工作表中

$Path = 'C:\folder\Test.xlsx' 
$Text='C:\folder\text.txt' 
# Open the Excel document and pull in the 'Play' worksheet 
$Excel = New-Object -Com Excel.Application 
$Excel.Visible=$true #For troubleshooting purposes only. 

$Workbook = $Excel.Workbooks.Open($Path) 
$page = 'Sheet1' 
$ws = $Workbook.worksheets | where-object {$_.Name -eq $page} 
# Set variables for the worksheet cells, and for navigation 

$cells=$ws.Cells 
$row=1 
$col=1 
$cells.item($Row,$col)=$Text 
$col++ 
# Close the workbook and exit Excel 
$workbook.Close($true) 
$excel.quit() 

回答

0

這是因爲您將$ Text設置爲文件的路徑。您必須使用像Get-Content這樣的cmdlet實際讀取文件的內容。

例如:

$Text = Get-Content 'C:\folder\text.txt' 

但是,根據該文本文件的內容,你可能想要做的不同,或者你可以用一個混亂的結果告終。

相關問題