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

Powershell - Copy and pasting last lines of TSV to specific Cells in Excel

好的,所以第 3 次有望让我到达那里。我已经在这个脚本上工作了一段时间,只需要一点帮助就可以让我完成任务。我正在尝试为 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

这对我有用...您可能需要根据您对工作表的命名稍作修改:

$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 不会 return 任何它只会在 excel 中打开它。