如何遍历bean的属性以填充电子表格的单元格

时间:2013-04-17 18:48:33

标签: excel apache-poi xpages

我正在使用POI从托管bean生成Excel电子表格。这是我的学生豆:

package edu.phc.students.model;

public class Student {
private String m_firstName; 
private String m_lastName; 
private String m_id;

public Student() {} 

public Student(
String firstName, 
String lastName, 
String id,
) 
{ 
        m_firstName=firstName; 
        m_lastName=lastName;   
        m_id=id;

} 

public String getid() { 
        return m_id; 
} 

public void setid(String newid) { 
        m_id=newid; 
} 

public String getFirstname() { 
        return m_firstName; 
} 

public void setFirstname(String newFirstName) { 
        m_firstName=newFirstName; 
} 

public String getLastname() { 
        return m_lastName; 
} 

public void setLastname(String newLastname) { 
        m_lastName=newLastname; 
}    

}

这是最终代码(SSJS)的一小部分。

var students:java.util.List = studentlist.getStudents();
var iterator:java.util.Iterator = students.iterator();
var count = 0;
while (iterator.hasNext()) {
        var student:edu.phc.students.model.Student = iterator.next();
        count++;
        var row:HSSFRow = sheet1.createRow(count);
        for( f = 0 ; f <= fieldList.length-1 ; f++){//column List
            // output student's data into Excel row 
            row.createCell((java.lang.Integer)(f)).setCellValue(student.getid());               
        }
}

这完美无缺。它使用列名生成电子表格,并将学生ID插入每个单元格(对于迭代器返回的每一行)。

但是,我想迭代学生bean的可用属性 - ID,姓氏,名字等,并填充电子表格的单元格。我怎么做?我可以通过索引来引用学生bean的属性吗?

谢谢,

1 个答案:

答案 0 :(得分:1)

您可以使用 java.lang.reflection 。以下是学生班中所有字段的示例:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

   <xp:repeat id="repeat1" rows="30" var="field">
      <xp:this.value><![CDATA[#{javascript: 
         var student = new edu.phc.students.model.Student();
         student.getClass().getDeclaredFields()}]]>
      </xp:this.value>
      <xp:label value="#{field.name}" id="labelFieldName" /><xp:br />
   </xp:repeat>
</xp:view>

输出如下:

m_firstName
m_lastName
m_id

请查看documentation for other options

修改

此示例迭代方法并返回返回String的所有方法的当前值:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

<xp:repeat id="repeat1" rows="30" var="method">
    <xp:this.value><![CDATA[#{javascript: 
        var student = new edu.phc.students.model.Student();
        student.setid("A");
        student.setLastname("Meiser");
        student.setFirstname("Hans");
        student.getClass().getDeclaredMethods()}]]>
    </xp:this.value>
    <xp:label id="label1">
        <xp:this.value>
            <![CDATA[#{javascript:
                if( method.getReturnType().getSimpleName()  == 'String' )
                    return method.invoke(student, null );}]]>
        </xp:this.value>
    </xp:label>
    <xp:br />
</xp:repeat>

</xp:view>

这将创建以下输出:

A

Hans

Meiser