导出到第二+电子表格

时间:2016-08-11 20:25:10

标签: export-to-excel excel-2013 powershell-v4.0

我正在使用Export-Csv导出[pscustomobject]。然后我使用第二个函数将其转换为xlsx。哪个效果很好。但是如果我想导出到第二个电子表格并将其重命名为不同的东西呢? 我知道Export-Csv不支持多张电子表格。

Function SaveAsXLXS
{
    #Hide Old File
    (Get-Item $ResultsFilePath -Force).Attributes = "Hidden"

    #Opens Old File
    $Excel = New-Object -ComObject Excel.Application
    $Workbook = $Excel.Workbooks.Open($ResultsFilePath)

    #Formating
    if ($GroupsTab.IsSelected -or $OrgBoxesTab.IsSelected)
    {
        $Workbook.Worksheets.Item(1).Columns.Item(1).Font.Bold = $True
        $Workbook.Worksheets.Item(1).Columns.Item(1).Font.Size = 12
    }
    $Workbook.Worksheets.Item(1).Rows.Item(1).Font.Bold = $True
    $Workbook.Worksheets.Item(1).Rows.Item(1).Font.Size = 15
    $Workbook.Worksheets.Item(1).UsedRange.EntireColumn.Autofit()

    #Creates Name for New File
    $ExcelOut = $ResultsFilePath -replace '\.csv$', '.xlsx'
    $dir = Split-Path $ExcelOut
    $FilePathBase = $(Split-Path $ExcelOut -Leaf) -replace '\.xlsx$'
    $FilePath = $ExcelOut

    $n = 1
    while (Test-Path $FilePath) {
        $FilePath = Join-Path $dir $($FilePathBase + "-$n" + '.xlsx')
        $n++
    }

    #Saves New File
    $Workbook.SaveAs($FilePath, 51)

    #Exits Old File
    $Excel.Quit()

    #Removes Old File
    Remove-Item $ResultsFilePath -Force
}

1 个答案:

答案 0 :(得分:1)

您将CSV作为新工作簿打开,因此您只需要打开要添加它的工作簿,然后移动/复制工作表。

...
$Workbook = $Excel.workbooks.open($ResultsFilePath)
...

$wb2 = $Excel.Workbooks.Open('C:\path\to\other.xlsx')
$Workbook.Sheets.Item(1).Name = 'whatever'          # rename sheet
$Workbook.Sheets.Item(1).Copy($wb2.Sheets.Item(1))  # copy sheet
$Workbook.Close($false)                             # close CSV without saving
$wb2.Save()                                         # save & close workbook
$wb2.Close()

当然,如果要将多个CSV插入工作簿,只需打开一次xlsx文件,并在插入所有工作表后保存/关闭它。

如果要在目标工作簿中的特定工作表之后插入CSV中的工作表,请将Copy()调用更改为以下内容:

$Workbook.Sheets.Item(1).Copy([Type]::Missing, $wb2.Sheets.Item(3))