[英]Convert ArrayList of objects to Object Array for jasperreports
好。 這里有一個新手大問題,但我一直在徒勞地尋找解決方案。
使用在這里找到的示例,我可以在報表中使用customdatasource。
但是...該示例將這段代碼用於粘貼為數據的實際對象
private Object[][] data =
{
{"Berne", new Integer(22), "Bill Ott", "250 - 20th Ave."},
{"Berne", new Integer(9), "James Schneider", "277 Seventh Av."},
{"Boston", new Integer(32), "Michael Ott", "339 College Av."},
{"Boston", new Integer(23), "Julia Heiniger", "358 College Av."}, etc...
不幸的是,java不允許動態地添加到該Object數組,並且由於報表數據始終是動態的,因此變得毫無用處。
我已經嘗試了一個自定義數據類,該類具有添加到ArrayList的兩個元素,例如
ArrayList<myDataObject> a = new ArrayList<myDataObject>();
for(int x=0;x<5;x++){
myDataObject myl = new myDataObject("asdasd",Integer.toString(x));
a.add(myl);
}
但是(這是newbee的一部分)我似乎無法弄清楚如何將其轉換為jasper期望的簡單Object [] []。
這是我正在使用的數據類
import java.util.ArrayList;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
public class CustomData implements JRDataSource {
private Object data[][];
private int index;
// public CustomData(Object o[][]) {
// index = -1;
// this.data = o;
// }
public CustomData(ArrayList <Object> a) {
index = -1;
this.data = (Object)a.toArray();
}
public boolean next() throws JRException {
index++;
return (index < data.length);
//throw new UnsupportedOperationException("Not supported yet.");
}
public Object getFieldValue(JRField field) throws JRException {
Object value = null;
String fieldName = field.getName();
if ("aName".equals(fieldName)) {
value = data[index][0];
}
else if ("aNumber".equals(fieldName)) {
value = data[index][1];
}
return (String)value;
// throw new UnsupportedOperationException("Not supported yet.");
}
}
任何幫助都會很棒。
只需簡單地遍歷列表並將其添加到二維數組即可:
public static void main(String[] args) {
ArrayList<MyDataObject> a = new ArrayList<MyDataObject>();
for(int x=0;x<5;x++){
MyDataObject myl = new MyDataObject("asdasd", Integer.toString(x));
a.add(myl);
}
int aSize = a.size();
Object[][] thingy = new Object[aSize][2];
for(int i = 0; i < aSize; i++) {
MyDataObject mdo = a.get(i);
thingy[i][0] = mdo.getS();
thingy[i][1] = mdo.getI();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.