Powershell excel worksheets move

  • Remove From My Forums
  • Question

  • How can I use powershell to move a worksheet from an existing open excel file to another open existing excel file.  Note, I don’t want to create a new excel file which is what «$excel.worksheets.item(«name of worksheet to move»).move()» does. 

Answers

  • I’m not sure if you’ve figured something out already…

    move needs to know where to move the sheet. You can specify to move it before or after a sheet in the same workbook or in another workbook. move will move the sheet to a new workbook if it doesn’t know where to put it.

    I’m still trying to get comfortable with powershell and excel, so here is a vbscript that hopefully, you can convert to powershell. I used sheet instead of worksheet because sheet can be charts or worksheets.

    'moves "sheet1" in book1.xls to book2.xls
    'it is moved before 1st sheet in book2.xls
    
    set xl = createobject("excel.application")
    
    xl.visible = true
    
    set wbSrc = xl.workbooks.open("c:scriptsbook1.xls")
    set wbDst = xl.workbooks.open("c:scriptsbook2.xls")
    
    wbSrc.sheets("sheet1").move wbDst.sheets(1)
    

    Hopefully, soon, I can do this comfortably in powershell,
    Francis

    • Edited by

      Monday, August 31, 2009 4:15 AM
      s

    • Marked as answer by
      IamMred
      Saturday, January 9, 2010 3:00 AM

I’d like to copy (or move) a worksheet from one workbook to another workbook with Powershell.

I had done this before and cant remember how. I think I used CopyTo() function.

Just to get started.

$missing = [System.Type]::missing
$excel = New-Object -Com Excel.Application

$wb1 = $excel.Workbooks.Add($missing)
$wb2 = $excel.Workbooks.Add($missing)

# Now, to copy worksheet "Sheet3" from $wb2 into $wb1 as second worksheet.
# How?

Community's user avatar

asked Jul 12, 2010 at 5:37

idazuwaika's user avatar

See post from Kiron

Changed index to copy to second sheet:

$file1 = 'C:UsersericDocumentsBook1.xlsx' # source's fullpath
$file2 = 'C:UsersericDocumentsBook2.xlsx' # destination's fullpath
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item(2) # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('Sheet3') # source sheet to copy
$sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook
$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

answered Jul 12, 2010 at 5:42

dugas's user avatar

dugasdugas

11.9k2 gold badges44 silver badges51 bronze badges

1

Mikey Bronowski

Mikey Bronowski

I am Mikey: Husband, Dad, SQL DBA, MCT, Microsoft Data platform MVP

  • Website
  • Twitter
  • GitHub
  • LinkedIn
  • stackoverflow
  • StackExchange

less than 1 minute read

You May Also Enjoy

The SQLBits 2023 experience

:uk:

5 minute read

In March 2023 we visited Newport, Wales to attend our third in-person SQLBits. Here is how it was for us.

T-SQL Tuesday 159 — New Year’s Resolutions — Magda

:uk:

1 minute read

This month the #TSQL2SDAY invitation comes from Deepthi Goguri who asks us to write about our favorite new feature in SQL Server 2022 or in Azure and New Yea…

T-SQL Tuesday 159 — What’s Your Favorite New Feature? — Magda

:uk:

3 minute read

This month the #TSQL2SDAY invitation comes from Deepthi Goguri who asks us to write about our favorite new feature in SQL Server 2022 or in Azure and New Yea…

T-SQL Tuesday 150 — My first technical job

:uk:

3 minute read

This month the #TSQL2SDAY invitation comes from Kenneth Fisher who asks us to write about our first technical job.

Вопрос:

Я занимаюсь этим довольно долгое время,

Я хочу создать новый рабочий лист, скопировав другой. Это помещает новый лист перед копированием листа. Затем я хочу переместить его до самого конца всех листов.

Цель состоит в том, чтобы рабочие листы назывались > summary1 > summary2 > summary3.. и т.д. в этом порядке

Вот что я имею (извините краткость)

$ex = New-Object -ComObject Excel.Application
$ex.Visible = $true
$wb = $ex.Workbooks.Add()

for ($i = 1; $i -le 3; $i++)
{
$wb.Worksheets.Item(2).Copy($wb.Worksheets.Item(2))
$newSheet = $wb.Worksheets.Item(2)
$newSheet.Activate()
$name = "Summary$i"
$newSheet.Name = $name
$wb.Worksheets.Item($name).Move($wb.Worksheets.Item($i + 1))
}

Он работает для первого листа, он переименовывает лист и перемещает его до конца, но после этого каждый раз, когда он достигает метода .Move, он ничего не делает, кроме .Activate() исходный лист “Сводка”.

Я понятия не имею, как объяснить это поведение. Спасибо, пожалуйста, заранее.

Изменить: Изменено $wb.Worksheets.Item( “Сводка” ). Перейдите к $wb.Worksheets.Item($ name).Move

Edit:

Вот решение:

for ($i = 1; $i -le 3; $i++)
{
$wb.Worksheets.Item(2).Copy($wb.Worksheets.Item(2))
$newSheet = $wb.Worksheets.Item(2)
$newSheet.Activate()
$name = "Summary$i"
$newSheet.Name = $name

$lastSheet = $wb.WorkSheets.Item($wb.WorkSheets.Count)
$newSheet.Move([System.Reflection.Missing]::Value, $lastSheet)
}

Ответ №1

Отмечено как Сообщество, потому что это из вопроса выше.

Вот решение:

for ($i = 1; $i -le 3; $i++)
{
$wb.Worksheets.Item(2).Copy($wb.Worksheets.Item(2))
$newSheet = $wb.Worksheets.Item(2)
$newSheet.Activate()
$name = "Summary$i"
$newSheet.Name = $name

$lastSheet = $wb.WorkSheets.Item($wb.WorkSheets.Count)
$newSheet.Move([System.Reflection.Missing]::Value, $lastSheet)
}

Ответ №2

Я могу предложить более “общий” и, возможно, более быстрый ответ, только ради его использования. Просто имейте в виду, что это от VBA и потребует незначительных изменений для запуска в той же среде, что и ваш вопрос.

Sub sheetCopier()
Dim destSht As Object, srcSht As Object, NewShts As Long, shtCnt As Long

Set srcSht = ThisWorkbook.Sheets(2)

For NewShts = 1 To 5
shtCnt = ThisWorkbook.Sheets.Count
srcSht.Copy after:=ThisWorkbook.Sheets(shtCnt)
Set destSht = ThisWorkbook.Sheets(shtCnt + 1)
destSht.Name = "New Sht" & Format(NewShts, "00")
Next
Set srcSht = Nothing
Set destSht = Nothing

End Sub

очевидно, что может вас заинтересовать:

shtCnt = ThisWorkbook.Sheets.Count
srcSht.Copy after:=ThisWorkbook.Sheets(shtCnt)
Set destSht = ThisWorkbook.Sheets(shtCnt + 1)
destSht.Name = "New Sht" & Format(NewShts, "00")

а остальные – просто запустить демонстрацию.

вы можете делать вещи с еще меньшим количеством кода, но это не так приятно:

thisworkbook.sheets(2).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = "New Sht" & Format(NewShts, "00")

поэтому я предполагаю (но не могу подтвердить), что ваш код может быть написан как:

for ($i = 1; $i -le 3; $i++)
{
$wb.Worksheets(2).Copy(,$wb.Worksheets($wb.Worksheets.count))
$name = "Summary$i"
$wb.Worksheets($wb.Worksheets.count).Name = $name
}

просто обратите внимание, что синтаксис копирования:.copy([before], [after]) с опциями до и после. В vba следующие способы: .copy after:=ASheetObject или .copy ,aSheetObject

веселит

In this blog post I will demonstrate how to create the Excel Report below using PowerShell and data from the AdventureWorks2012 database.

SalesYTD

1. Creating a New Excel Workbook

In this step we will be creating a new Excel Workbook

#Open a new Excel Workbook
$EXCL = New-Object -ComObject Excel.Application
$EXCL.Visible = $true
$WB = $EXCL.Workbooks.Add()

2. Rename a Worksheet

In this step we will be renaming “Sheet1” to “Worksheet1”.

#Rename Worksheets
$SHEET = $EXCL.WorkSheets.item("Sheet1")
$SHEET.Name = "Worksheet1"

3. Add a new Worksheet

In this step we will be adding a new Worksheet and the name will be “Sheet4”

#Add WorkSheets
$SHEET = $EXCL.WorkSheets.add()
$SHEET = $workbook.ActiveSheet

4. Move Worksheets Order

In this step we will moving worksheet “Sheet3” to be in front of Worksheet “Sheet4”

#Move Worksheets
$SHEET1 = $EXCL.sheets.item("Sheet3");
$SHEET2 = $EXCL.sheets.item("Sheet4"); 
$SHEET1.Move($SHEET2)

5. Delete a Worksheet

In this step we will be deleting Worksheet “WorkSheet3”

#Delete Sheet3
$DeleteSheet = $EXCL.sheets.item("Sheet3");
$DeleteSheet.delete()

6. Add Report Title

In this step we will add a report title  of “AdventureWorks Sales Year to Date By Country”, change the text to bold and change the text size to 16 pt. We are also going to Merge A1,B1,C1 cell together, change the font color to white, change the fill color to Green and change the Alignment to the middle.

#Add Report Title
$SHEET = $EXCL.WorkSheets.item("Sheet2")
$SHEET.Cells.Item(1,1) = 'AdventureWorks Sales Year to Date By Country'
$SHEET.Cells.Item(1,1).Font.Bold=$True
$SHEET.Cells.Item(1,1).Font.size=16
$SHEET.Range("A1:C1").MergeCells =$True
$SHEET.Range("A1:C1").Interior.ColorIndex = 10  #Fill Color Green
$SHEET.Range("A1:C1").Font.ColorIndex = 2
$SHEET.Range("A1:C1").HorizontalAlignment = -4108  #Alignment Middle
#Right Alignment -4152
#Left Alignment -4131

7. Add Column Titles

In this step we will add three column titles in row 2, change the text to bold and change the column width

#Add Column Titles
$SHEET = $EXCL.sheets.item("Sheet2")
$SHEET.Cells.Item(2,1) = 'CountryRegionCode'
$SHEET.Cells.Item(2,1).Font.Bold=$True
$SHEET.Columns.item(1).ColumnWidth=23
$SHEET.Cells.Item(2,2) = 'SalesYTD'
$SHEET.Columns.item(2).ColumnWidth=18
$SHEET.Cells.Item(2,2).Font.Bold=$True
$SHEET.Cells.Item(2,3) = 'SalesLastYear'
$SHEET.Cells.Item(2,3).Font.Bold=$True
$SHEET.Columns.item(3).ColumnWidth=18

8. Create DataTable

In this step I am selecting data from the AdventureWorks2012 SQL Server Database. Note in the $Datatable variable you will need to enter your SQL Server Name in the “-ServerInstane” parameter.

function Invoke-Sqlcmd3

{
    param(
    [string]$Query,             
    [string]$Database="tempdb",
    [Int32]$QueryTimeout=30
    )
    $conn=new-object System.Data.SqlClient.SQLConnection
    $conn.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $Server,$Database
    $conn.Open()
    $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
    $cmd.CommandTimeout=$QueryTimeout
    $ds=New-Object system.Data.DataSet
    $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
    [void]$da.fill($ds)
    $conn.Close()
    $ds.Tables[0]
}

#Create DataTable with our report data
[String]$TSQL= "
use AdventureWorks2012

SELECT 
CountryRegionCode
,sum(SalesYTD) as SalesYTD
,SUM(SalesLastYear) as SalesLastYear
FROM AdventureWorks2012.Sales.SalesTerritory
GROUP BY CountryRegionCode
ORDER BY CountryRegionCode
"
$Datatable = Invoke-Sqlcmd3 -ServerInstance [Enter SQL Server Name] -Database AdventureWorks2012 -Query $TSQL -as 'DataTable'

9. Populate the Worksheet

In this step starting in row 3 we will be populating the Worksheet with data from the DataTable that was created in step 8.

#Populate the Worksheet
$SHEET = $EXCL.sheets.item("Sheet2")
$x=3
$Datatable | FOREACH-OBJECT{
$SHEET.cells.item($x, 1) =  $_.CountryRegionCode
$SHEET.cells.item($x, 2) =  $_.SalesYTD
$SHEET.cells.item($x, 3) =  $_.SalesLastYear
$x++
}

10. Clean Up

In this Step we will rename “WorkSheet2” to “SalesYTD” and delete worksheets “WorkSheet1” and “sheet4”.

#Clean Up
#Rename Sheet2 to SalesYTD
$SHEET = $EXCL.sheets.item("Sheet2")
$SHEET.Name = "SalesYTD"
#Delete Worksheet and sheet4
$DeleteSheet = $EXCL.sheets.item("WorkSheet1");
$DeleteSheet.delete() 
$DeleteSheet = $EXCL.sheets.item("sheet4");
$DeleteSheet.delete()

11. Save the Excel File

In this step we will save the Excel file to C:TempSalesYTD.xlsx

#Save Excel File to C:TempSalesYTD.xlsx
$SHEET = $EXCL.sheets.item("SalesYTD")
$SHEET.SaveAs("C:tempSalesYTD.xlsx")

Понравилась статья? Поделить с друзьями:
  • Powershell excel from csv
  • Powerpivot для microsoft excel 2013 скачать
  • Power query выгрузить в excel
  • Powershell data from excel
  • Powerpivot для excel 2019 скачать