Copy Data From One Spreadsheet to Another

July 04, 2011

Copies data from one Excel spreadsheet to another.
PowerShell
$comments = @'  
Script name: Copy-ExcelData.ps1  
Created on: Wednesday, August 22, 2007  
Author: Kent Finkle  
Purpose: How can I use Windows Powershell to  
Copy Data From One Spreadsheet to Another?  
'@  
# -----------------------------------------------------  
function Release-Ref ($ref) {  
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(  
[System.__ComObject]$ref-gt 0)  
[System.GC]::Collect()  
[System.GC]::WaitForPendingFinalizers()  
}  
# -----------------------------------------------------  
$xl = new-object -comobject excel.application  
$xl.Visible = $True  
$wb = $xl.Workbooks.Add()  
$ws = $wb.Worksheets.Item("Sheet1")  
  
$2d = new-object 'object[,]' 20,1  
 
for ($i = 0; $i -le 19; $i++) {  
    for ($j = 0; $j -le 0; $j++) {  
        $2d[$i,$j] = $i  
    }  
}  
  
$r = $ws.Range("A1:A20")  
$r.Value() = $2d  
$a = $r.Copy()  
  
$xl2 = new-object -comobject excel.application  
$xl2.Visible = $True  
$wb2 = $xl2.Workbooks.Add()  
$ws2 = $wb2.Worksheets.Item("Sheet1")  
$a = $ws2.Paste()  
  
$a = Release-Ref($ws2)  
$a = Release-Ref($wb2)  
$a = Release-Ref($xl2)  
$a = Release-Ref($ws)  
$a = Release-Ref($wb)  
$a = Release-Ref($xl
Verified on the following platforms
 
Windows Server 2008 R2No
Windows Server 2008No
Windows Server 2003No
Windows 7No
Windows VistaNo
Windows XPNo
Windows 2000No
This script is tested on these platforms by the author. It is likely to work on other platforms as well. If you try it and find that it works on another platform, please add a note to the script discussion to let others know.

Related Posts

Next Article
« Prev Post
Previous Article
Next Post »

No comments