如何仅将可见的 excel 列导出到 csv?

How to export only visible excel columns to csv?

好的,所以有像 这样的线程只将可见行导出到 csv,但是列呢?我需要一个循环吗?还是可以像可见的工作表一样轻松完成?

Begin {
    $excel = New-Object -ComObject Excel.Application -Property @{
        Visible       = $false
        DisplayAlerts = $false
    }
}
Process {
    #$root = Split-Path -Path $Path
    $filename = [System.IO.Path]::GetFileNameWithoutExtension($Path)
    $workbook = $excel.Workbooks.Open($Path)

    foreach ($worksheet in ($workbook.Worksheets | Where { <# $_.Visible -eq -1 #> $_.Name -ne 'Security' -and $_.Name -ne 'Notes' })) {
        <#  WIP     
        if($ExcludeHiddenColumns) {
            if ($worksheet.Column.Visible -eq -1) {
                $worksheet.sheets.columns.entirecolumn.hidden=$true
            }
        } #>

        if ($ExcludeHiddenSheets) {
            if ($worksheet.Visible -eq -1) {
                $ws = $worksheet
            }
        }
        else {
            $ws = $worksheet
        }

        if ($AppendFileName) {
            $name = Join-Path -Path $csvPATH <# $root #> -ChildPath "${filename}_$($ws.Name).csv"
        }
        else {
            $name = Join-Path -Path $csvPATH <# $root #> -ChildPath "$($ws.Name).csv"
        }

        try {
            $ws.SaveAs($name, 6) #6 to ignore formatting and convert to pure text, otherwise, file could end up containing rubbish
        } 
        catch {
            Write-Error -Message "Failed to save csv! Path: '$name'. $PSItem"
        }
    }
}

特别是,如果布尔参数 $ExcludeHiddenColumns 指定,这是我正在努力告诉脚本仅导出可见列的部分,但不确定处理此问题的最佳方法..

    <#  WIP     
    if($ExcludeHiddenColumns) {
        if ($worksheet.Column.Visible -eq -1) {
            $worksheet.sheets.columns.entirecolumn.hidden=$true
        }
    } #>

经过反复试验,我想通了!

foreach ($worksheet in ($workbook.Worksheets | Where { <# $_.Visible -eq -1 #> $_.Name -ne 'Security' -and $_.Name -ne 'Notes' })) {
    if($ExcludeHiddenColumns) {
        $ColumnsCount = $worksheet.UsedRange.Columns.Count
        for ($i=1; $i -le $ColumnsCount; $i++)
        {
            $column = $worksheet.Columns.Item($i).EntireColumn #$worksheet.sheets.columns.entirecolumn.hidden=$true
            if ($column.hidden -eq $true)
            {
                $columnname = $column.cells.item(1,$i).value2
                "Column {0} was deleted!" -f $columnname
                $column.Delete()
                #$i = $i - 1
            }
        }
    }
}