[英]Copying Text File Data into existing Excel Workbook Using PowerShell
所以我在將數據從Text.File導出到包含一個月數據的Excel工作簿時遇到問題。 最終發生的事情是,該代碼打開了一個新工作簿 ,名稱和標題為“ Geraldine3-16-2016”,但我不介意,但是它從未添加或復制到主工作簿中。 因此,最終,主工作簿中唯一發生變化的是創建了一個名為“ Sheet 1”的新工作表,但文本文件中沒有數據。 非常感謝您的幫助,在此先謝謝您!
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
$File='C:\users\cesar.sanchez\downloads\Returns data 2-16-15.xlsx'
$TextFile='C:\Users\cesar.sanchez\downloads\Geraldine3-16-2016.txt'
$Excel = New-Object -C Excel.Application
$Excel.Visible=$true #For troubleshooting purposes only.
# $Excel.DisplayAlerts = $false
$TextData = $Excel.Workbooks.Opentext($TextFile,$null,$true)
$ExcelData = $Excel.Workbooks.Open($File) # Open Template
$NewS_ExcelData=$ExcelData.sheets.add()
$TexttoCopy=$TextData.Sheets.item(1)
$TexttoCopy.copy($NewS_ExcelData)
我相信這與代碼的這一部分內容有關,但我不確定。
$NewS_ExcelData=$ExcelData.sheets.add()
$TexttoCopy=$TextData.Sheets.item(1)
$TexttoCopy.copy($NewS_ExcelData)
.OpenText
與.Open
。 它不返回對象。 (找出困難的方法!)
$TexttoCopy=$TextData.Sheets.item(1)
引發錯誤:
You cannot call a method on a null-valued expression.
備用代碼:
$File='C:\users\cesar.sanchez\downloads\Returns data 2-16-15.xlsx'
$TextFile='C:\Users\cesar.sanchez\downloads\Geraldine3-16-2016.txt'
$Excel = New-Object -C Excel.Application
$Excel.Visible=$true #For troubleshooting purposes only.
# $Excel.DisplayAlerts = $false
$Excel.Workbooks.Opentext($TextFile,$null,$true) # Open Text file
$TextData = $Excel.ActiveWorkbook # Assign active workbook
$ExcelData = $Excel.Workbooks.Open($File) # Open Template
$NewS_ExcelData = $ExcelData.sheets.add()
$TexttoCopy = $TextData.Sheets.item(1)
$TexttoCopy.copy($NewS_ExcelData)
您可能還會發現$TexttoCopy.move($NewS_ExcelData)
有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.