0

So I have a PowerShell script which copies the data from an source xls file to a destination xlsx file. Assume I have file named "3 ABC01.xls" and I have to insert the data present in this xls file into an sheet named ABC01 in the destination file xlsx. So I have written the following logic


$csvFilePath = Read-Host "Enter the CSV File path"
$data = Import-Csv -Path $csvFilePath
$startRowNumber = 5
$firstRowNumber = 5
$lastRowNumber = 15


$destExcel = New-Object -ComObject Excel.Application
$destExcel.DisplayAlerts = $false
$destExcel.Visible = $false
$destWorkbook = $destExcel.Workbooks.Open("destination.xlsx")
foreach ($line in $data) {
    $column1 = $line.column1
    $column2 = $line.column2
    
    $tamlineString = $column1 + " " + $column2
    $sourceFilePath = "$downloadDirectory\$column1\$tamlineString.xls"
    
    $excel = New-Object -ComObject Excel.Application
    $excel.DisplayAlerts = $false
    $excel.Visible = $false
    $sourceWorkbook = $excel.Workbooks.Open($sourceFilePath)
    $sourceWorksheet = $sourceWorkbook.Sheets.Item(1)
    
    $worksheetName = $column2 + $sheet
    Write-Host $worksheetName
    $destWorksheet = $destWorkbook.Sheets.Item($worksheetName)

    
    # Loop through the rows to copy and insert
    for ($i = $lastDateRowNumber - 1; $i -ge $firstRowNumber; $i--) {
        $sourceRange = $sourceWorksheet.Rows.Item($i)
        # Copy the source row
        $sourceRange.Copy() | Out-Null
        # Insert a new row in the destination worksheet
        $destWorksheet.Rows.Item($startRow).Insert() | Out-Null
        
        # Get the newly inserted row
        $destRow = $destWorksheet.Rows.Item($startRow) 
        
        # Paste values and formatting from the clipboard
        $destRow.PasteSpecial(-4163) | Out-Null  # -4163 represents 'Paste All' in Excel
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($destRow) | Out-Null
        $destRow = $null
    }

    
    # Close and quit the source workbook
    #$sourceWorksheet.Close()
    $destWorkbook.Save()
    $sourceWorkbook.Close()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sourceWorksheet)| Out-Null
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sourceWorkbook)| Out-Null

    # Quit Excel application
    $excel.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)| Out-Null
    
    Write-Host "Rows copied and inserted successfully for $column1 $column2."
}

$destWorkbook.Save()
$destWorkbook.Close()

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($destWorksheet) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($destWorkbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($destExcel) | Out-Null

And I am running the above code, and getting the below exception inconsistently, like sometimes I get the exception and sometimes I dont get the exception.

Microsoft Excel cannot paste the data.
At D:\Users\Shyam\script.ps1:37 char:17
+                 $destRow.PasteSpecial(-4163) | Out-Null  # -4163 repr ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

I am not able to get why am I getting this exception? Can anyone help me in explaining what is going on? Thank you!! for your time

I tried adding the extra Start-Sleep -Milliseconds 100 inside the for loop before copying the data after inserting the row, etc.. but again I was getting the same error.

I am expecting to run this script and it should not give me the exception while running the script. It should successfully paste the data.

12
  • You have XLS, not XLSX (excel). XLSX is a proprietary binary file while XLS is Text. Commented Oct 28, 2023 at 8:15
  • Hello @jdweng, I have modified the $destWorkbook variable, so if there was any confusion now it might have resolved, So I want to transfer the data from XLS file to XLSX file. I am sorry if I didnt got what you mean, can you please explain in detail what you meant? Commented Oct 28, 2023 at 8:24
  • Do not mix xls and xlsx they are not the same. Your variable $startRow is not initialized. Commented Oct 28, 2023 at 12:07
  • 2
    .xls is a binary file. Try Format-Hex -Path the.xls. .xlsx is a text file. It was created to represent XML in order to convince potential customers, especially in the EU, that it was not proprietary and was open to interoperating with other software. Has it worked out that way? Commented Oct 28, 2023 at 12:07
  • Have you tried the same sequence manually? You might be trying to paste into merged cells for example, and the UI may give a better error message than the COM interface does… Commented Oct 29, 2023 at 2:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.