【发布时间】:2012-10-06 18:14:18
【问题描述】:
为什么在 VBScript 中将单元格值写入 Excel 比在 PowerShell 中快得多? PowerShell 不是新事物,VBScript 不是已弃用的 MS 脚本语言吗?
VBScript 示例(保存到文件名.vbs) 这会在瞬间运行。
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = false
Set objWorkbook = objExcel.Workbooks.Add()
' Edit: increased number of writes to 500 to make speed difference more noticeable
For row = 1 To 500
'Edit: using .cells(row,1) instead of .cells(50,1) - this was a mistake
objWorkbook.workSheets(1).cells(row,1).value = "test"
Next
objWorkbook.SaveAs(CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\test.xlsx")
objExcel.Quit
msgbox "Done."
PowerShell 示例(保存到 filename.ps1) 这需要几秒钟才能运行(数千条记录有问题)
#need this to work around bug if you use a non-US locale: http://support.microsoft.com/default.aspx?scid=kb;en-us;320369
[System.Threading.Thread]::CurrentThread.CurrentCulture = "en-US"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $False
$xls_workbook = $excel.Workbooks.Add()
# Edit: using foreach instead of for
# Edit: increased number of writes to 500 to make speed difference more noticeable
foreach ($row in 1..500) {
# Edit: Commented out print-line, slows down the script
#"Row " + $row
# This is very slow! - http://forums.redmondmag.com/forums/forum_posts.asp?tid=4037&pn=7
$xls_workbook.sheets.item(1).cells.item($row,1) = "test"
}
$xls_workbook.SaveAs($MyInvocation.MyCommand.Definition.Replace($MyInvocation.MyCommand.Name, "") + "test.xlsx")
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
我想将它用于数千条记录。如果没有快速的方法来做到这一点,PowerShell 不是一个选项。有更好的选择吗?
【问题讨论】:
-
更多的“权力”通常伴随着更多的资源需求stackoverflow.com/questions/9343413/…
标签: excel optimization powershell vbscript powershell-2.0