Wou*_*ter 5 vbscript excel powershell optimization powershell-2.0
为什么在VBScript中将单元格值写入Excel要比在PowerShell中快得多?PowerShell不是新东西,而VBScript是不推荐使用的MS脚本语言吗?
VBScript示例(保存到filename.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."
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
我想将它用于成千上万的记录.如果没有快速的方法,PowerShell不是一个选项.还有更好的选择吗?
您可以通过不循环单个单元格来加快速度:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $True
$xls_workbook = $excel.Workbooks.Add()
$range = $xls_workbook.sheets.item(1).Range("A1:A100")
$range.Value2 = "test"
Run Code Online (Sandbox Code Playgroud)
如果你想在一个范围内写一个值数组,这里有一篇很好的博客文章,演示了类似的技巧:
如何使用PowerShell快速将数据导入Excel电子表格