【问题标题】:Convert XLS to XLSB Programmatically?以编程方式将 XLS 转换为 XLSB?
【发布时间】:2011-09-20 12:36:08
【问题描述】:

我有一位客户需要将 XLS 文件转换为 XLSB。有没有人以编程方式完成此操作(有或没有附加组件 --- 没关系 --- 只需要能够自动化它)?我正在寻找一种自动化的方法。

作为旁注,客户之所以问这个问题是因为他们使用 Sharepoint,而且它似乎有一种比 XLS 更快、更容易分析 XLSB 文件的方法?我正在努力提高我的 Sharepoint 知识,但与此同时,我正在努力寻找这个 XLSB 问题的答案。

【问题讨论】:

  • 如果您可以使用早期绑定Office Interop,这将相当容易。请指定其他限制。可以保存和操作本地磁盘上的文件吗?
  • @Petr - 是的,我可以保存和操作本地磁盘上的文件。
  • 您使用 MS Office VBA 转换它。

标签: c# vb.net sharepoint binary xls


【解决方案1】:

那么,有一个简短的格式版本:

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();

您将需要一个带有 .NET 编程支持的 Excel 安装(在安装程序中默认禁用!)并从您的项目中为 Excel 引用 MS Office PIA 程序集:

参考资料: Workbooks.Open、workbook.SaveAs、XlFileFormat.xlExcel12

【讨论】:

    【解决方案2】:

    我编写此 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='alb@coaxis.com'
    
        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
    

    【讨论】:

    • 脚本中是否可能存在流程,因为当尝试在没有选择文件夹对话框的情况下运行它时(我将这些行放在注释下) - 它只是不会执行转换。我从 Windows 'cmd' 运行它......我正在使用示例部分中显示的命令......难道我作为参数提供给 powershell.exe 的“-ExecutionPolicy Bypass”会以某种方式干扰吗?
    【解决方案3】:

    This 可以在命令行中使用。

    【讨论】:

    • 它似乎只支持转换 from (不支持) .xlsb :( 这让我感到惊讶,因为它似乎使用 Excel COM Interop for the .xlsb,它应该保存它就像加载它一样容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2013-02-09
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多