将XML数据写入xls的Groovy脚本(Excel)

utugiqy6  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

我有一个如下的XML结构。如何编写一个groovy脚本将XML数据写入xls(Excel)?有人能帮助我吗?

<Record>
  <Action>create</Action>
  <ID KEMASAN>DUS, 1 BOTOL PLASTIK @ 28 TABLET</ID KEMASAN>
  <Barcode>(01)00372626270113(21)200000022671(17)(10)ICS_DECOM</Barcode>
  <Barcode>(01)00372626270113(21)200000022670(17)(10)ICS_DECOM</Barcode>
  <Barcode>(01)00372626270113(21)200000000052(17)(10)ICS_DECOM</Barcode>
  <NIE>DKI1844200317A1</NIE>
  <LOT NO>ICS_DECOM</LOT NO>
  <Exp Date>31/12/2024</Exp Date>
  <Batch No>ICS_DECOM</Batch No>
  <GTIN>00372626270113</GTIN>
  <IS_ACTIVE>TRUE</IS_ACTIVE>
  <IS_SAMPLE>FALSE</IS_SAMPLE>
  <IS_REJECT>FALSE</IS_REJECT>
  <MFG DATE>01/01/2023</MFG DATE>
  <Case SGTIN>urn:epc:id:sgtin:0372626.527011.200000000052</Case SGTIN>
  <Pallet SGTIN>urn:epc:id:sscc:0361958.0001046962</Pallet SGTIN>
</Record>

字符串

nvbavucw

nvbavucw1#

我建议使用spreadsheet.dsl.builders。您的XML无效,因为它包含标记名称的空格(即<ID KEMASAN><Batch No>等),所以我在空格处添加了下划线,并能够运行以下内容:

@Grab('builders.dsl:spreadsheet-builder-poi:3.0.1')
@Grab('builders.dsl:spreadsheet-builder-groovy:3.0.1')
import builders.dsl.spreadsheet.builder.poi.PoiSpreadsheetBuilder

def xml = new XmlSlurper().parseText('''
<root>
    <Record>
      <Action>create</Action>
      <ID_KEMASAN>DUS, 1 BOTOL PLASTIK @ 28 TABLET</ID_KEMASAN>
      <Barcode>(01)00372626270113(21)200000022671(17)(10)ICS_DECOM</Barcode>
      <Barcode>(01)00372626270113(21)200000022670(17)(10)ICS_DECOM</Barcode>
      <Barcode>(01)00372626270113(21)200000000052(17)(10)ICS_DECOM</Barcode>
      <NIE>DKI1844200317A1</NIE>
      <LOT_NO>ICS_DECOM</LOT_NO>
      <Exp_Date>31/12/2024</Exp_Date>
      <Batch_No>ICS_DECOM</Batch_No>
      <GTIN>00372626270113</GTIN>
      <IS_ACTIVE>TRUE</IS_ACTIVE>
      <IS_SAMPLE>FALSE</IS_SAMPLE>
      <IS_REJECT>FALSE</IS_REJECT>
      <MFG_DATE>01/01/2023</MFG_DATE>
      <Case_SGTIN>urn:epc:id:sgtin:0372626.527011.200000000052</Case_SGTIN>
      <Pallet_SGTIN>urn:epc:id:sscc:0361958.0001046962</Pallet_SGTIN>
    </Record>
</root>
''')

File output = new File("spreadsheet.xlsx")

PoiSpreadsheetBuilder.create(output).build {
    sheet("My Sheet") {
        xml.Record.each { r ->
            row {
                cell "Action"
                cell "ID"
                cell "Batch Number"
                cell "NIE"
            }
            row {
                cell r.Action.text()
                cell r.ID_KEMASAN.text()
                cell r.Batch_No.text()
                cell r.NIE.text()
            }
        }
    }
}
println("Done! ${output.absolutePath}")

字符串

相关问题