Преобразовать XLS в XLSB программно?

У меня есть клиент, которому нужно преобразовать файлы XLS в XLSB. Кто-нибудь делал это программно (с надстройкой или без --- не имеет значения --- просто нужно уметь это автоматизировать)? Я ищу способ автоматизировать это.

В качестве примечания, клиент спрашивает об этом, потому что он использует Sharepoint, и кажется, что у него есть способ анализировать файлы XLSB быстрее и проще, чем XLS? Я работаю над улучшением своего знания Sharepoint, а пока пытаюсь найти ответ на эту проблему с XLSB.


person John Cruz    schedule 22.06.2011    source источник
comment
Это довольно просто, если вы можете использовать раннее связывание Office Interop. Укажите дополнительные ограничения. Можете ли вы сохранять и работать с файлами на локальном диске?   -  person Petr Abdulin    schedule 27.06.2011
comment
@Petr - Да, я могу сохранять и работать с файлами на локальном диске.   -  person John Cruz    schedule 27.06.2011
comment
Вы конвертируете его с помощью MS Office VBA.   -  person dns    schedule 13.03.2018


Ответы (3)


Ну а дальше краткий формат версии:

using Microsoft.Office.Interop.Excel;

// init excel
Application excelApplication = new Application();

// ...

// open book in any format
Workbook workbook = excelApplication.Workbooks.Open("1.xls", XlUpdateLinks.xlUpdateLinksNever, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

// save in XlFileFormat.xlExcel12 format which is XLSB
workbook.SaveAs("1.xlsb", XlFileFormat.xlExcel12, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

// close workbook
workbook.Close(false, Type.Missing, Type.Missing);

// ...

// shutdown excel
excelApplication.Quit();

Вам понадобится установка Excel с поддержкой программирования .NET (по умолчанию отключена в установщике!) и ссылка на сборку MS Office PIA для Excel из вашего проекта:

добавить ссылку Excel PIA

Ссылки: Workbooks.Open, workbook.SaveAs, XlFileFormat.xlExcel12

person Petr Abdulin    schedule 27.06.2011

Я пишу этот код powershell для рекурсивного преобразования многих файлов *.xls во многие папки. этот скрипт предлагает выбрать папку, преобразовать все файлы и удалить оригинал (переместить в корзину), отобразить каждое имя файла в консоли powershell.

<#
    .SYNOPSIS
    Covert all *.xls files recursivly in a provided path
    .DESCRIPTION
    XLS files within a provided path are recursively enumerated and convert to XLSB files (with macro).
    The original XLS files are deleted if newfile has created (in trash), a new XLSb file replace the old file.
    #>
    $autor='alban Lopez'
    $version=0.85
    $email='[email protected]'

    function ConvertTo-XLSB {
    <#
    .SYNOPSIS
    XLS files within a provided path are recursively enumerated and convert to XLSB files.
    .DESCRIPTION
    XLS files within a provided path are recursively enumerated and convert to XLSB files.
    The original XLS files remain intact, a new XLSB file will be created.
    .PARAMETER Path
    This parameter takes the input of the path where the XLS files are located.
    .PARAMETER Visible
    Using the parameter will show you how Excel does the work. Not using the parameter will enable Excel 
    to accomplish its tasks in the background.
    Note: Bu not using this parameter you will be able to convert some XLS files which have corruptions 
    in them, when using the parameter and therefor the Excel GUI will give you an error.
    .PARAMETER ToFolder
    This parameter enables you to provide a location where the file is saved. When this parameter is 
    not used, the file will be saved as an XLS file in the same location as where the 
    original XLS file is located.
    .EXAMPLE
    ConvertTo-XLSB -Path 'D:\Data\2012'
    .EXAMPLE
    ConvertTo-XLSB -Path 'D:\Data\2012' -Visible
    .EXAMPLE
    ConvertTo-XLSB -Path 'D:\Data\2012' -ToFolder 'D:\Data\2012XLSB'
    .EXAMPLE
    ConvertTo-XLSB -Path 'D:\Data\2012' -Visible -ToFolder 'D:\Data\2012XLSB'
#>
    [cmdletbinding()]

        param (
            [parameter(mandatory=$true)][string]$Path,
            [parameter(mandatory=$false)][switch]$Visible,
            [parameter(mandatory=$false)][string]$ToFolder
        )
        begin {
            $Excel = New-Object -ComObject excel.application
            $Excel.DisplayAlerts = $false
            # $xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault # xlsx
            $xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlExcel12 # 50 = xlsb
            $shell = new-object -comobject "Shell.Application"

            $count = 0
            $count_OK = 0
            $count_Nok = 0

            if ($Visible -eq $true) {
                $Excel.visible = $true
            } else {
                $Excel.visible = $false
            }
            $filetype = "*xls"
        } process {
            if (Test-Path -Path $Path) {
                Get-ChildItem -Path $Path -Include '*.xls' -recurse | ForEach-Object {
                    if ($ToFolder -ne '') {
                        $FilePath = Join-Path $ToFolder $_.BaseName
                    } else {
                        $FilePath = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
                    }
                    $FilePath += ".xlsb"
                    $WorkBook = $Excel.workbooks.open($_.fullname)
                    $WorkBook.saveas($FilePath, $xlFixedFormat)
                    $WorkBook.close()
                    $OldFolder = $Path.substring(0, $Path.lastIndexOf("\")) + "\old"
                    if (test-path $FilePath){
                        $count_OK++
                        Write-Host -nonewline "$count_OK > "
                        Write-Host $_.fullname -ForegroundColor Cyan
                        $item = $shell.Namespace(0).ParseName("$($_.fullname)")
                        $item.InvokeVerb("delete")
                    } else {
                        $count_Nok++
                        Write-Host -nonewline "$count_Nok > "
                        Write-Host $_.fullname -ForegroundColor red
                    }
                    $count++
                }
            } else {
                return 'No path provided or access has been denied.'
            }
        } end {
            Write-Host '========================================================' -ForegroundColor yellow
            Write-Host -nonewline "Total : $count";
            Write-Host -nonewline " / Erreurs : $count_Nok / " -ForegroundColor red;
            Write-Host "convertis : $count_ok" -ForegroundColor green;
            Write-Host '========================================================' -ForegroundColor yellow

            $Excel.Quit()
            $Excel = $null
            [gc]::collect()
            [gc]::WaitForPendingFinalizers()
        }
    }


#=============================================================================
# Displays a select file dialog box, returning the path to a CSV file.
#=============================================================================
function Read-FolderBrowserDialog([string]$Message, [string]$InitialDirectory)
{
    $app = New-Object -ComObject Shell.Application
    $folder = $app.BrowseForFolder(0, $Message, 0, $InitialDirectory)
    if ($folder) { return $folder.Self.Path } else { return $false }
}

''
'Choisir le dossier source >'
$source = Read-FolderBrowserDialog -Message "Dossier source"

while ($source)
{
    "Convertion de tous les fichiers du dossier : $source"
    $ConvTime = Measure-Command {ConvertTo-XLSB -Path $source}
    Write-Host "$($ConvTime.Hours):$($ConvTime.Minutes):$($ConvTime.Seconds)";
    ''
    "End"
    ''
    'Choisir le dossier source >'
    $source = Read-FolderBrowserDialog -message "Dossier source" -InitialDirectory $source
    #$dest = Select-FolderDialog -message "Dossier Destination (sera conservé)" -RootFolder $source
}
start-sleep -s 30
person Alban    schedule 10.02.2014
comment
Есть ли в скрипте какой-то поток, так как при попытке запустить его без диалогового окна выбора папки (эти строчки я поставил под комментарием) - он просто не выполнит преобразование. Я запускаю его из Windows 'cmd' ... Я использую именно те команды, которые показаны в разделе ПРИМЕРЫ ... Может ли быть так, что -ExecutionPolicy Bypass, который я указываю в качестве параметра для powershell.exe, как-то мешает? - person GWD; 23.04.2015

Это можно использовать из командной строки.

person Dave Ziegler    schedule 30.06.2011
comment
Похоже, он поддерживает только преобразование из (не в) .xlsb :( что меня удивляет, поскольку, похоже, для .xlsb используется COM-взаимодействие Excel, что должно сделать его сохранение таким же простым, как загрузка Это. - person Aaron Thoma; 09.03.2012