如何使用速度模板中的动态数据准备表格?

时间:2019-04-19 13:29:18

标签: java velocity

我有一个需要在速度模板中生成动态表的要求。

我在Java代码下面,我正在准备一个哈希表。输入将来自外部应用程序。

public String generateFileFromStringTemplate(HashMap<String, Object> documentContentHashmap, String templateString,TWList list){
         System.out.println("hashmap : "+list.getArraySize());
         TWObject obj=null;
         Map<String, Map<String,String>> mapobj=new HashMap<>();
        try{
          TemplateUtility tutility = new TemplateUtility();
          obj = TWObjectFactory.createObject();
          for (int i = 0; i < list.getArraySize(); i++) {
            obj=(TWObject) list.getUnmodifiableArray().get(i);
            Object[]s=obj.getPropertyNames().toArray();
            Map<String, String> map1=new HashMap<>();
            for (int j = 0; j < obj.getPropertyNames().toArray().length; j++) {
                map1.put(s[j].toString(),(String) obj.getPropertyValue(s[j].toString()));
            }
            mapobj.put("Map"+i, map1);
          }
          documentContentHashmap.put("Map", mapobj);
          StringWriter strWriter = tutility.generateTemplateFromString(documentContentHashmap, templateString);

          String documentBytes = tutility.generateDocsEncodedToBase64Content(strWriter);
          if (documentBytes != null) {
            return documentBytes;
          }
          return null;
        }
        catch (Exception e){
          e.printStackTrace();
          return e.getMessage();
        }
      }
}

下面是我将documentContentHashmap传递给速度模板引擎的代码。

StringWriter generateTemplateFromString(HashMap<String, Object> documentContentHashmap, String templateString)
      {
        try
        {
          RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
          Date date = new Date();
          SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_HHmmss");
          String fileName = "StrTemplate_" + sdf.format(date) + ".html";
          StringReader reader = new StringReader(templateString);
          SimpleNode node = runtimeServices.parse(reader, fileName);
          Template template = new Template();
          template.setRuntimeServices(runtimeServices);
          template.setData(node);
          template.initDocument();
          VelocityContext context = new VelocityContext();
          Set<String> sourceKeySet = documentContentHashmap.keySet();
          System.out.println("sourceKeySet : "+sourceKeySet);
          for (String key : sourceKeySet) {
              System.out.println("documentContentHashmap.get(key) : "+documentContentHashmap.get(key));
            context.put(key, documentContentHashmap.get(key));
          }
          StringWriter writer = new StringWriter();
          template.merge(context, writer);
          return writer;
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
        return null;
      }

下面是从上面的代码生成的示例数据。

{Map0={interestRate=3, tenor=2 sal, proposedLimit=555, loanType=PL, approvedLimit=556, loanAmount=554, loanRepaymentDate=AAJ}, Map1={interestRate=1, tenor=3 sal, proposedLimit=445, loanType=HL, approvedLimit=446, loanAmount=444, loanRepaymentDate=KAL}}

下面是我的html,我在其中迭代地图并尝试将上面的数据显示为2行,但是我无法实现,因此所有数据仅显示在一行中。

<html>
<head>
<style type="text/css">

td,th{font-family:Arial, "Helvetica Neue", Helvetica, sans-serif;font-size:12px ;}
.PaymentVoucher{
    font-size:15px;
    text-align:center;
    letter-spacing: 3px;
}
</style>
</head>
<body>
<div>
<table style="width:100%; border: 1px solid #dddddd; font-family: Times New Roman, Times, sans-serif;">
<tr>
    <td  colspan="2">
        <label><b></b></label>
    </td>
    <td style="width:20%;">
    <span>Customer Name : $pvMap.get('customer_name')</span><br/>
    </td>
</tr>
<tr>
    <td style="width:20%;">
    <br />
        <label>Page &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</label><span>1 of 1</span>
    </td>
</tr>
<tr>
    <td colspan="4" class="PaymentVoucher"><b>Loan&nbsp; Details&nbsp;</b></td>
</tr>
<tr>

    <td>
        <label style="width:450px;">Loan Application Date : </label><span>$pvMap.get('application_date')</span>
    </td>
    <td colspan = "3"></td>
</tr>
</table>
<br />
<table  style="width:100%; border: 1px solid #dddddd; font-family: Times New Roman, Times, sans-serif;"> 
  <tr>
        <th>Loan Type</th><th>Loan Amount</th><th>Interest Rate</th><th>Loan Repayment Date</th><th>Tenor</th><th>Proposed Limit</th><th>Approved Limit</th>
  </tr>
  <tr>
    #set($str1="loanType")

    #set($str2="loanAmount")

    #set($str3="interestRate")

    #set($str4="loanRepaymentDate")

    #set($str5="tenor")

    #set($str6="proposedLimit")

    #set($str7="approvedLimit")

    #foreach ($mapEntry in $Map.entrySet())
        #foreach ($map1 in $mapEntry.getValue().entrySet())
            #if($map1.key==$str1)
                <td>$map1.getValue()</td>
            #end
        #end
    #end
    </tr>
</table>
<br />
<br />
<span>Regards,</span><BR/>
<span>Test</span><BR/>
</div>
</body>
</html>

有人可以帮上忙吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

尝试在第一个循环内移动第二个<tr>标签(并使用map getter而不是循环遍历条目,这就是制作地图的目的):

<table  style="width:100%; border: 1px solid #dddddd; font-family: Times New Roman, Times, sans-serif;"> 
  <tr>
        <th>Loan Type</th><th>Loan Amount</th><th>Interest Rate</th><th>Loan Repayment Date</th><th>Tenor</th><th>Proposed Limit</th><th>Approved Limit</th>
  </tr>
    #set($columns = ["loanType", "loanAmount", "interestRate", "loanRepaymentDate", "tenor", "proposedLimit", "approvedLimit"])
    #foreach ($subMap in $Map.values())
    <tr>
        #foreach ($column in $columns)
            <td>$subMap.get($column)</td>
        #end
    </tr>
    #end
</table>