2012-05-18 5 views
4

지금 당분간 스크립트를 작성하려고하지만 일부 기능이 작동하지 않는 것으로 보입니다.LibreOffice/OpenOffice Calc : VBscript, CSV로 XLS 시트 내보내기

상황 : 내가 많은으로 (모든 Windows XP 또는 CSV로 XLS의 수출을위한 7 시스템에 (내 경우에는 3.5.4) 모든 LibreOffice와 (/ 오픈 오피스) 석회질을 사용할 수있는 VB 스크립트 설치가 필요 CSV 파일 xls에 시트가 있음). 이 경우 VBS와 LibreOffice 여야합니다. 매크로가 설치되지 않았으며 모든 것이 외부에서 vbscript에 의해 제어되었습니다.

그래서 첫 번째 단계는 올바른 필터 설정을 얻기 위해 매크로 레코더를 사용하는 것이 었습니다.

스타 베이직 (StarBasic) 매크로 :

dim document as object 
    dim dispatcher as object 

    document = ThisComponent.CurrentController.Frame 
    dispatcher = createUnoService("com.sun.star.frame.DispatchHelper") 

    dim args1(2) as new com.sun.star.beans.PropertyValue 
    args1(0).Name = "URL" 
    args1(0).Value = "file:///C:/Users/lutz/Desktop/test.csv" 
    args1(1).Name = "FilterName" 
    args1(1).Value = "Text - txt - csv (StarCalc)" 
    args1(2).Name = "FilterOptions" 
    args1(2).Value = "9,0,76,1,,0,false,true,true" 

    dispatcher.executeDispatch(document, ".uno:SaveAs", "", 0, args1()) 

이 매크로 (LibreOffice와의) 현재 시트의 CSV (LO는 현재 시트가 저장 될 것을 말해 후), 인코딩을 기록 UTF-8 , 필드 구분 기호 탭, 텍스트 구분 기호 없음. 이 작동합니다.

나는 이것을 내 vbs에서 작동 시키려고했지만 절대적으로 그렇게하지 못했습니다. 그래서 저는 OpenOffice와 LibreOffice forums, 여기 stackoverflow 등에서 많은 것을 수색하고 또 다른 방법을 사용했습니다.

문제점 : 파일을 저장할 때마다 내가 사용하는 필터 또는 필터 옵션에 상관없이 파일을 ODS로 저장합니다. 항상 압축 된 OpenDocument로 저장됩니다. 나는 수많은 필터, 심지어 PDF를 시도했다. 그것은 내가 FilterName 속성을 사용하지만 어떻게 든 더 이상 작동하지 않는 경우 PDF와 함께 작동하는 것 같습니다. 왜 그런지 모르겠습니다.

코드 :

' Scripting object 
    Dim wshshell 
    ' File system object 
    Dim objFSO 
    ' OpenOffice/LibreOffice Service Manager 
    Dim objServiceManager 
    ' OpenOffice/LibreOffice Desktop 
    Dim objDesktop 
    ' Runcommand, if script does not run with Cscript 
    Dim runcommand 

    Dim Path 
    Dim Savepath 
    Dim Filename 

    Dim url 
    Dim args0(0) 
    Dim args1(3) 

    ' Create File system object 
    Set wshshell = CreateObject("Wscript.Shell") 
    Set objFSO = CreateObject("Scripting.FileSystemObject") 

    ' If not run in cscript, run in cscript 
    if instr(1, wscript.fullname, "cscript.exe")=0 then 
    runcommand = "cscript //Nologo xyz.vbs" 
    wshshell.run runcommand, 1, true 
    wscript.quit 
    end if 

    ' If files present, run Calc 
    If objFSO.GetFolder(".").Files.Count>0 then 
     Set objServiceManager = WScript.CreateObject("com.sun.star.ServiceManager") 
     ' Create Desktop 
     Set objDesktop = objServiceManager.createInstance("com.sun.star.frame.Desktop") 
    else 
     ' If no files in directory 
     wscript.echo "No files found!" 
     wscript.quit 
    End If 

    on error resume next 

    bError=False 
    For each File in objFSO.GetFolder(".").Files 
     if lcase(right(File.Name,3))="xls" then 

     ' Access file 
     url = ConvertToURL(File.Path) 
     objDesktop = GlobalScope.BasicLibraries.loadLIbrary("Tools") 
     Set args0(0) = objServiceManager.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
     Set objDocument = objDesktop.loadComponentFromURL(url, "_blank", 0, args0) 

     ' Read filenames without extension or path 
     Path = ConvertToURL(File.ParentFolder) & "/" 
     Filename = objFSO.GetBaseName(File.Path) 
     Savepath = ConvertToURL(File.ParentFolder) 

     ' set arguments 
     Set args1(0) = objServiceManager.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
     Set args1(1) = objServiceManager.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
     Set args1(2) = objServiceManager.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
     sFilterName = "Text - txt - csv (StarCalc)" 
     sFilterOptions = "9,0,76,1,,0,false,true,true" 
     sOverwrite = True 
     Set args1(0) = MakePropertyValue("FilterName", sFilterName) 
     Set args1(1) = MakePropertyValue("FilterOptions", sFilterOptions) 
     Set args1(2) = MakePropertyValue("Overwrite", sOverwrite) 

     ' Save every sheet in separate csv file 
     objSheets = objDocument.Sheets 
     For i = 0 to objDocument.Sheets.getcount -1 
      objSheet = objDocument.Sheets.getByIndex(i) 
      Call objDocument.CurrentController.setActiveSheet(objSheet) 
      Call objDocument.storeToURL(ConvertToURL(File.ParentFolder & "\" & Filename & "_" & objDocument.sheets.getByIndex(i).Name & ".csv"), args1) 
     Next 

     ' Close document 
     objDocument.close(True) 
     Set objDocument = Nothing 
     Path = "" 
     Savepath = "" 
     Filename = "" 

    Else 
    End If 

    Next 

    ' Close/terminate LibreOffice 
    objDesktop.terminate 
    Set objDesktop = nothing 
    Set objServiceManager = nothing 

기능 ConvertToUrl은 여기에 나열되지 않습니다. Windows 경로를 URL 경로 (file : /// 등)로 변환하는 vbscript 함수입니다. 테스트를 거쳐 작동합니다. 나는 또한 시도 무엇

: ODS 첫 번째 (StoreAsUrl)에서

  • 저장은 다른 형식으로 저장하려고합니다.
  • (true "로 SelectionOnly")를 사용 MakePropertyValue 그

아무도 일하지 않으며 결합했다. 영감의 원천으로 http://extensions.services.openoffice.org/de/project/OOcalc_multi_sheets_export을 사용했습니다. 하지만 그것은 외부 VB 스크립트에서 직접 액세스가 아닌 매크로입니다. 작동하지 않는 심지어는 FilterName "writer_pdf"또는 "Calc를 MS Excel 2007의 XML"

이 문제가 StoreToUrl 또는 등록/인수 일반적인 일 것 같다. 문제는 : 나는 여기서 범인이 무엇인지 모른다. 매크로 레코더가 사용하는 설정은 동일하며 LibreOffice에서 매크로를 직접 사용하는 경우 작동합니다.

아마도 누군가 코드에서 변경해야 할 사항이나 매크로에서 작동하는 디스패처를 얻는 방법을 알 수 있습니다.

미리 도움을 주셔서 감사합니다.

답변

6

좋아, 나는 연구의 며칠 후 솔루션을 발견하고 작은 정보가 사방에 흩어져. 이 코드가 아니라 사람이 될 것입니다 희망 :

' Variables 
Dim wshshell  ' Scripting object 
Dim oFSO   ' Filesystem object 
Dim runcommand ' Runcommand, if not run in Cscript 

Dim oSM  ' OpenOffice/LibreOffice Service Manager 
Dim oDesk  ' OpenOffice/LibreOffice Desktop 
Dim oCRef  ' OpenOffice/LibreOffice Core Reflections 

Dim sFileName ' Filename without extension 
Dim sLoadUrl ' Url for file loading 
Dim sSaveUrl ' Url for file writing 
Dim args0(0) ' Load arguments 

' Create file system object 
Set wshshell = CreateObject("Wscript.Shell") 
Set oFSO = CreateObject("Scripting.FileSystemObject") 

' If not run in cscript, run in cscript 
if instr(1, wscript.fullname, "cscript.exe")=0 then 
    runcommand = "cscript //Nologo xyz.vbs" 
    wshshell.run runcommand, 1, true 
    wscript.quit 
end if 

' If there are files, start Calc 
If oFSO.GetFolder(".").Files.Count>0 then 
    ' If no LibreOffice open -> run 
     Set oSM = WScript.CreateObject("com.sun.star.ServiceManager") 
    ' Create desktop 
     Set oDesk = oSM.createInstance("com.sun.star.frame.Desktop") 
     Set oCRef = oSM.createInstance("com.sun.star.reflection.CoreReflection") 
else 
    ' If no files in directory 
     wscript.quit 
End If 

' Error handling 
on error resume next 

' CSV settings for saving of file(s) 
sFilterName = "Text - txt - csv (StarCalc)" 
sFilterOptions = "9,0,76,1,,0,false,true,true" 
sOverwrite = True 

' load component for file access 
oDesk = GlobalScope.BasicLibraries.loadLIbrary("Tools") 

' load argument "hidden" 
Set args0(0) = oSM.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
Set args0(0) = MakePropertyValue("Hidden", True) 

For each oFile in oFSO.GetFolder(".").Files 
    if lcase(right(oFile.Name,3))="xls" then 
     ' open file 
     sLoadUrl = ConvertToURL(oFile.Path) 
     Set oDoc = oDesk.loadComponentFromURL(sLoadUrl, "_blank", 0, args0) 
     ' read filename without extension or path 
     sFileName = oFSO.GetBaseName(oFile.Path) 
     ' save sheets in CSVs 
     For i = 0 to oDoc.Sheets.getcount -1 
      oActSheet = oDoc.CurrentController.setActiveSheet(oDoc.Sheets.getByIndex(i)) 
      sSaveUrl = ConvertToURL(oFile.ParentFolder & "\" & sFileName & "_" & oDoc.sheets.getByIndex(i).Name & ".csv") 
      saveCSV oSM, oDoc, sSaveUrl, sFilterName, sFilterOptions, sOverwrite 
     Next 
     ' Close document 
     oDoc.close(True) 
     Set oDoc = Nothing 
     Set oActSheet = Nothing 
     sFileName = "" 
     sLoadUrl = "" 
     sSaveUrl = "" 
    Else 
    End If 
Next 

' Close LibreOffice 
oDesk.terminate 
Set oDesk = nothing 
Set oSM = nothing 


Function ConvertToURL(sFileName) 
' Convert Windows pathnames to url 

Dim sTmpFile 

If Left(sFileName, 7) = "file://" Then 
    ConvertToURL = sFileName 
    Exit Function 
End If 

ConvertToURL = "file:///" 
sTmpFile = oFSO.GetAbsolutePathName(sFileName) 

' replace any "\" by "/" 
    sTmpFile = Replace(sTmpFile,"\","/") 

' replace any "%" by "%25" 
    sTmpFile = Replace(sTmpFile,"%","%25") 

' replace any " " by "%20" 
    sTmpFile = Replace(sTmpFile," ","%20") 

ConvertToURL = ConvertToURL & sTmpFile 
End Function 


Function saveCSV(oSM, oDoc, sSaveUrl, sFilterName, sFilterOptions, sOverwrite) 
' Saves the open document resp. active sheet in a single file 

Dim aProps(2), oProp0, oProp1, oProp2, vRet 

' Set filter name and write into property array 
    Set oProp0  = oSM.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
    oProp0.Name  = "FilterName" 
    oProp0.Value = sFilterName 
    Set aProps(0) = oProp0 

' Set filter options and write into property array 
    Set oProp1  = oSM.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
    oProp1.Name  = "FilterOptions" 
    oProp1.Value = sFilterOptions 
    Set aProps(1) = oProp1 

' Set file overwrite and write into property array 
    Set oProp2  = oSM.Bridge_GetStruct("com.sun.star.beans.PropertyValue") 
    oProp2.Name  = "Overwrite" 
    oProp2.Value = sOverwrite 
    Set aProps(2) = oProp2 

' Save 
    vRet   = oDoc.storeToURL(sSaveUrl, aProps) 

End Function 

나는 내에서 적어도이 작은 기여가 다른 사람을 도움이되기를 바랍니다.