Powershell - 将最后一行TSV复制并粘贴到Excel中的特定单元格

时间:2017-11-09 15:55:57

标签: excel powershell copy-paste

好的,所以第三次有希望能让我到那儿。我已经在这个脚本上工作了一段时间,只需要一些帮助就可以让我超越终点线。我正在尝试为powershell编写一个脚本,该脚本采用TAB分隔文件的最后X行(在本例中为8行)并将其粘贴到我创建的Excel模板中的特定单元格中。我已经批量尝试了这个并且VBS无济于事。

到目前为止,这是我提出的代码:

 $pathtsv = “C:\test.txt” | Select -Last 8
 $pathxlsx = “C:\NBP ESP-152 REV F TEMPLATE.xlsx”
 $Excel = New-Object -ComObject excel.application
 $Excel.visible = $true
 $Workbook = $excel.Workbooks.open($pathtsv)
 $Workbook2 = $excel.Workbooks.open($pathxlsx)
 $Worksheet = $Workbook.WorkSheets.item(“Overview”)
 $Worksheet.activate()
 $range = $WorkSheet.Range(“A3:J10”).CurrentRegion
 $range.Copy() | out-null
 $Worksheet2 = $Workbook2.Worksheets.item(“RAW DATA”)
 $worksheet2.activate()
 $range2 = $Worksheet2.Range(“A3:A3”)
 $Worksheet2.Paste($range2)
 $Excel.Quit()
 [gc]::collect()
 [gc]::WaitForPendingFinalizers()

以下是我尝试复制的TSV文件示例:

09/29/17    12:49:31    NBP 00022   10.013  5955.000    7.198   0.309   24.017  60.658  CW          
            20.057  0.000   0.091   0.000   0.000   0.000   CW
            31.050  5954.000    7.094   0.302   24.016  61.432  CCW
            41.083  0.000   0.547   0.000   0.000   0.000   CCW
            47.081  0.000   78.460  2.104   4.515   0.000   CW
            52.099  0.000   82.710  2.156   4.516   0.000   CCW
            57.234  0.000   103.000 2.858   6.217   0.000   CW
            62.247  0.000   111.000 2.887   6.216   0.000   CCW

以下是我试图粘贴的模板(@ A,3)。

highlight shows where it is to be pasted

1 个答案:

答案 0 :(得分:1)

这对我有用......你可能需要稍微改变一下,这取决于你的名字:

$pathtsv = "\test.txt"
$pathxlsx = "\NBP ESP-152 REV F TEMPLATE.xlsx"

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true 

$Workbook = $Excel.Workbooks.Open($pathxlsx) # Open Template
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv) # Open text file in excel

$temp = $excel.Workbooks.Item(2)  #select workbook with text
$temp = $temp.Worksheets.Item(1) #select text worksheet
$CopyRange = $temp.Range("A1:G8") #set range
$CopyRange.Copy()  #copy data

$workbooksheet = $Workbook.Worksheets.Item(1)#sets doc to copy to
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("A3:J10") #sets range
$workbooksheet.Paste($PasteRange)#paste data

#save and close the workbook
$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()

请注意$Excel.Workbooks.Opentext不会返回任何只在Excel中打开它的内容。