作为我正在构建的 Java 应用程序的一部分,需要打开两个 excel 文件,将数据从文件 A 复制到文件 B,用新名称保存文件 B,然后关闭这两个文件。目前我有一个完成此任务的 VBScript,java 通过以下方式调用:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cscript " + pathtovbscript);
当通过 Java 程序调用此脚本时,它似乎运行良好,并且没有抛出任何错误,但是当我转到目标目录搜索生成的 Excel 文件时,它不存在。我知道它正在打开 excel,因为如果我在程序执行时正在查看任务管理器,我可以看到它出现。
最后,如果我通过命令行手动调用脚本,一切正常,并创建新文件。
关于可能导致这种情况的任何想法?
下面的VBScript:
Dim destworkbook
Dim excel
Dim currsave
Dim sourceexcellist
sourcepath = path1
destpath = path2
sourcetab = tabname1
desttab = tabname2
savepath = savepathname
desttablist = Split(desttab, ",")
sourcelist = Split(sourcepath, ",")
sourcetablist = Split(sourcetab, ",")
destlist = Split(destpath, ",")
savelist = Split(savepath, ",")
Wscript.Echo "Number of Sources: " + Cstr(UBound(sourcelist)+1)
If UBound(desttablist) = UBound(sourcelist) And UBound(sourcelist) = UBound(sourcetablist) And UBound(sourcetablist) = UBound(destlist) Then
WScript.Echo "Arguments Equal"
Else
Wscript.Echo "Error: Arguments Invalid"
Wscript.Echo "Dest Tabs: " + Cstr(UBound(desttablist))
Wscript.Echo "Source Tabs: " + Cstr(UBound(sourcetablist))
Wscript.Echo "Sources: " + Cstr(UBound(sourcelist))
Wscript.Echo "Destinations: " + Cstr(UBound(destlist))
Wscript.Quit
End If
i=0
j=0
Set excel = CreateObject("Excel.Application")
For Each source in sourcelist
Wscript.Echo "Opening Excel"
If i>0 Then
lastdest = destlist(i-1)
Wscript.Echo "Last Destination file is " + lastdest
End If
Wscript.Echo "Creating Excel Object"
Wscript.Echo "Opening Workbook Located at " + sourcelist(i)
Set sourceWorkbook = excel.Application.Workbooks.Open(sourcelist(i))
excel.Application.DisplayAlerts = False
excel.Application.Visible = False
Wscript.Echo "Opening Workbook Located at " + destlist(i)
If lastdest <> destlist(i) Then
Wscript.Echo "Last Template Not Equal To Current Template"
destWorkbook.close
If Err.Number <> 0 Then
Wscript.Echo "No Active Excel"
Err.Clear
End If
Set destWorkbook = excel.Application.Workbooks.Open(destlist(i))
currsave = savelist(j)
Wscript.Echo "Current Save Path is " + currsave
j=j+1
End If
Wscript.Echo "Copying Range in " + sourcetablist(i)
sourceWorkbook.Sheets(sourcetablist(i)).UsedRange.Copy
Wscript.Echo "Activating Destination Range in " +desttablist(i)
destWorkbook.Sheets(desttablist(i)).Activate
destWorkbook.Sheets(desttablist(i)).Range("A1").Select
Wscript.Echo "Pasting data"
destWorkbook.Sheets(desttablist(i)).Paste
sourceWorkbook.close
Wscript.Echo "Saving results at " + currsave
destWorkbook.SaveAs Filename:=currsave
Wscript.Echo "Quitting Source File at " + sourcelist(i)
excel.Application.Workbooks.Activate(sourcelist(i))
sourceWorkbook.Activate
excel.Application.Quit
sourceexcellist(i) = sourceExcel
i=i+1
Next
For Each w in excel.Application.Workbooks
Wscript.Echo "Closing Workbook"
w.close
Next
Wscript.Echo "Closing Excel"
excel.Application.quit