【问题标题】:Is there a faster way to parse an excel document with Powershell?有没有更快的方法来使用 Powershell 解析 excel 文档?
【发布时间】:2013-03-10 07:22:15
【问题描述】:

我正在通过PowershellMS Excel 文档进行交互。每个 excel 文档可能有大约 1000 行数据。

目前,该脚本似乎读取Excel 文件并以每0.6 秒1 条记录的速率将值写入屏幕。乍一看,这似乎非常缓慢。

这是我第一次阅读带有PowershellExcel 文件,这是常态吗?有没有更快的方法来读取和解析Excel 数据?

这是脚本输出(为了便于阅读而进行了修剪)

PS P:\Powershell\ExcelInterfaceTest> .\WRIRMPTruckInterface.ps1 test.xlsx
3/20/2013 4:46:01 PM
---------------------------
2   078110
3   078108
4   078107
5   078109
<SNIP>
242   078338
243   078344
244   078347
245   078350
3/20/2013 4:48:33 PM
---------------------------
PS P:\Powershell\ExcelInterfaceTest>

这是Powershell 脚本:

########################################################################################################
# This is a common function I am using which will release excel objects
########################################################################################################
function Release-Ref ($ref) {
    ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

########################################################################################################
# Variables
########################################################################################################

########################################################################################################
# Creating excel object
########################################################################################################
$objExcel = new-object -comobject excel.application 

# Set to false to not open the app on screen.
$objExcel.Visible = $False

########################################################################################################
# Directory location where we have our excel files
########################################################################################################
$ExcelFilesLocation = "C:/ShippingInterface/" + $args[0]

########################################################################################################
# Open our excel file
########################################################################################################
$UserWorkBook = $objExcel.Workbooks.Open($ExcelFilesLocation) 

########################################################################################################
# Here Item(1) refers to sheet 1 of of the workbook. If we want to access sheet 10, we have to modify the code to Item(10)
########################################################################################################
$UserWorksheet = $UserWorkBook.Worksheets.Item(2)

########################################################################################################
# This is counter which will help to iterrate trough the loop. This is simply a row counter
# I am starting row count as 2, because the first row in my case is header. So we dont need to read the header data
########################################################################################################
$intRow = 2

$a = Get-Date
write-host $a
write-host "---------------------------"

Do {

    # Reading the first column of the current row
    $TicketNumber = $UserWorksheet.Cells.Item($intRow, 1).Value()

    write-host $intRow " " $TicketNumber    

    $intRow++

} While ($UserWorksheet.Cells.Item($intRow,1).Value() -ne $null)

$a = Get-Date
write-host $a
write-host "---------------------------"

########################################################################################################
# Exiting the excel object
########################################################################################################
$objExcel.Quit()

########################################################################################################
#Release all the objects used above
########################################################################################################
$a = Release-Ref($UserWorksheet)
$a = Release-Ref($UserWorkBook) 
$a = Release-Ref($objExcel)

【问题讨论】:

    标签: excel powershell


    【解决方案1】:

    Robert M. Toups, Jr. 在他的博客文章 Speed Up Reading Excel Files in PowerShell 中解释说,虽然加载到 PowerShell 的速度很快,实际上读取 Excel 单元格却很慢。另一方面,PowerShell 可以非常快速地读取文本文件,因此他的解决方案是在 PowerShell 中加载电子表格,使用 Excel 的原生 CSV 导出过程将其保存为 CSV 文件,然后使用 PowerShell 的标准Import-Csv cmdlet 来处理数据快得惊人。他报告说,这使他的导入过程加快了 20 倍!

    利用 Toups 的代码,我创建了一个 Import-Excel 函数,让您可以非常轻松地导入电子表格数据。 我的代码添加了在 Excel 工作簿中选择特定工作表的功能,而不仅仅是使用默认工作表(即保存文件时的活动工作表)。如果省略–SheetName 参数,则使用默认工作表。

    function Import-Excel([string]$FilePath, [string]$SheetName = "")
    {
        $csvFile = Join-Path $env:temp ("{0}.csv" -f (Get-Item -path $FilePath).BaseName)
        if (Test-Path -path $csvFile) { Remove-Item -path $csvFile }
    
        # convert Excel file to CSV file
        $xlCSVType = 6 # SEE: http://msdn.microsoft.com/en-us/library/bb241279.aspx
        $excelObject = New-Object -ComObject Excel.Application  
        $excelObject.Visible = $false 
        $workbookObject = $excelObject.Workbooks.Open($FilePath)
        SetActiveSheet $workbookObject $SheetName | Out-Null
        $workbookObject.SaveAs($csvFile,$xlCSVType) 
        $workbookObject.Saved = $true
        $workbookObject.Close()
    
         # cleanup 
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbookObject) |
            Out-Null
        $excelObject.Quit()
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelObject) |
            Out-Null
        [System.GC]::Collect()
        [System.GC]::WaitForPendingFinalizers()
    
        # now import and return the data 
        Import-Csv -path $csvFile
    }
    

    Import-Excel 使用这些补充功能:

    function FindSheet([Object]$workbook, [string]$name)
    {
        $sheetNumber = 0
        for ($i=1; $i -le $workbook.Sheets.Count; $i++) {
            if ($name -eq $workbook.Sheets.Item($i).Name) { $sheetNumber = $i; break }
        }
        return $sheetNumber
    }
    
    function SetActiveSheet([Object]$workbook, [string]$name)
    {
        if (!$name) { return }
        $sheetNumber = FindSheet $workbook $name
        if ($sheetNumber -gt 0) { $workbook.Worksheets.Item($sheetNumber).Activate() }
        return ($sheetNumber -gt 0)
    }
    

    【讨论】:

    • Import-CSV 是否让您能够选择特定的单元格和列数据?
    • 命令行实用程序的最佳实践(追溯到 Unix 时代)是它应该做好 one 的事情。所以 Import-Csv 只是导入整个东西。但是您只需应用 PowerShell 的强大功能,通常是 Where-Object 选择行,Select-Object 选择列。
    • 嗯,我会检查一下。会很困难,因为 excel 数据的格式不一致。一整天的柱状数据并不统一。我会玩它看看。我可能需要让 powershell 将 excel 文档按原样保存为 CSV,因为不会有任何用户交互来获取这些文档。
    • 这工作速度超快而且很棒!我唯一的问题是它在使用“é”和“ê”等特殊字符时遇到了困难。我尝试了不同类型的 CSV 数字,但似乎都不起作用。
    • 太棒了!解决方案很简单。而不是改变值$xlCSVType = 6,我不得不改变这个Import-Csv -path $csvFile -Encoding Default。希望它可以帮助任何人:)
    【解决方案2】:

    如果数据是静态的(不涉及公式,只是单元格中的数据),您可以将电子表格作为 ODBC 数据源进行访问,并对它执行 SQL(或至少类似于 SQL)查询。查看this reference 以设置您的连接字符串(工作簿中的每个工作表都将是本练习的“表”),并使用System.Data 像查询常规数据库一样查询它(Don Jones 写了一个wrapper function 这可能会有所帮助)。

    应该比启动 Excel 并逐个单元格地挑选要快。

    【讨论】:

    • 这个很有意思,我明天试试看效果如何。
    • 这很棒。快得离谱。
    猜你喜欢
    • 1970-01-01
    • 2012-04-22
    • 2021-07-29
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    相关资源
    最近更新 更多