﻿// determine plants in EORD
CreateTable V[plants] plant

Set V[table] "EORD"
Set V[fields] "WERKS"
Set V[orderby] "WERKS"
Set V[ABAPTRUE] "X"

Call /guixt/dbselect _
  export.table="table" _
  export.fields="fields" _
  export.orderby="orderby" _
  export.distinct="ABAPTRUE" _
  import.values="plants"


// temporary file
Set V[tempfile] "&%[TEMP]\xl.&V[today_y-m-d hms].csv"

// Excel output file
Set V[xlfile]  "E:\temp\xltest.xlsx"

// neededfields from EORD and LFA1
CreateTable V[slist] werks matnr vdatu bdatu lifnr name1

Set V[table] "EORD join LFA1 on LFA1~LIFNR = EORD~LIFNR"
Set V[fields] "EORD~WERKS,EORD~MATNR,EORD~VDATU type D,EORD~BDATU type D,EORD~LIFNR,LFA1~NAME1"
Set V[orderby] "EORD~WERKS,EORD~MATNR,EORD~VDATU"

// start Excel
CallJS XL_start 

// plant index
Set V[k] 0

label next_plant
if V[k<&V[plants.rowcount]]
  Set V[k] &V[k] + 1
  Set V[current_plant] "&V[plants.plant.&V[k]]"
  Set V[condition] "EORD~WERKS = '&V[current_plant]' "
  
  // read plant data
  Call /guixt/dbselect _
    export.table="table" _
    export.fields="fields" _
    export.condition="condition" _
    export.orderby="orderby" _
    import.values="slist"
  
  // generate text file (CSV-format)
  CopyText fromTable=V[slist] toText="temp" delimiter=";"
  CopyText fromText="temp" toFile="&V[tempfile]"  -utf8
  
  // copy as new worksheet
  CallJS XL_copy_textfile "&V[tempfile]" "Plant &V[current_plant]"
  
  // next one
  goto next_plant
endif

CallJS XL_save  "&V[xlfile]" 
CallJS XL_close

// remove temp file
RemoveFile "&V[tempfile]"


Message "Excel file &V[xlfile] generated" -statusline
Return